express的代码

    1. const express = require('express');
    2. const app = express();
    3. // 跨域 CORS
    4. app.use(require('./corsMiddleware'));
    5. app.use('/api/student', require('./api/student'));
    6. // 处理错误的中间件函数
    7. app.use(require('./errorMiddleware'));
    8. app.listen(5000, () => {
    9. console.log('监听端口');
    10. });

    判断请求

    1. const allowOrigin = ['null', 'http://127.0.0.1:5500'];
    2. module.exports = (req, res, next) => {
    3. //判断预检请求
    4. if(req.method === 'OPTIONS') {
    5. res.header(
    6. 'Access-Control-Allow-Methods',
    7. req.headers['access-control-request-method']
    8. );
    9. res.header(
    10. 'Access-Control-Allow-Headers',
    11. req.headers['access-control-request-headers']
    12. );
    13. }
    14. // 当携带cookie
    15. res.header('Access-Control-Allow-Credentials', true);
    16. // 判断简单请
    17. if ('origin' in req.headers && allowOrigin.includes(req.headers['origin'])) {
    18. res.header('Access-Control-Allow-Origin', req.headers['origin']);
    19. }
    20. next()
    21. }