express的代码
const express = require('express');
const app = express();
// 跨域 CORS
app.use(require('./corsMiddleware'));
app.use('/api/student', require('./api/student'));
// 处理错误的中间件函数
app.use(require('./errorMiddleware'));
app.listen(5000, () => {
console.log('监听端口');
});
判断请求
const allowOrigin = ['null', 'http://127.0.0.1:5500'];
module.exports = (req, res, next) => {
//判断预检请求
if(req.method === 'OPTIONS') {
res.header(
'Access-Control-Allow-Methods',
req.headers['access-control-request-method']
);
res.header(
'Access-Control-Allow-Headers',
req.headers['access-control-request-headers']
);
}
// 当携带cookie
res.header('Access-Control-Allow-Credentials', true);
// 判断简单请
if ('origin' in req.headers && allowOrigin.includes(req.headers['origin'])) {
res.header('Access-Control-Allow-Origin', req.headers['origin']);
}
next()
}