第一种方法
app.all("*",function(req,res,next){
//设置允许跨域的域名,*代表允许任意域名跨域
res.header("Access-Control-Allow-Origin","http://localhost:8081");
//允许的header类型
res.header("Access-Control-Allow-Headers","content-type");
//跨域允许的请求方式
res.header("Access-Control-Allow-Methods","DELETE,PUT,POST,GET,OPTIONS");
if (req.method.toLowerCase() == 'options')
res.send(200); //让options尝试请求快速结束
else
next();
});
第二种方法,原理是一样的,完整实例,把POST参数以JSON返回响应给客户端
const express = require('express');
const bodyParser = require('body-parser');
const { json } = require('body-parser');
const app = express();
//想要通过req.body得到post参数,先用这个中间件
app.use(bodyParser.urlencoded({ extended: false }));
//跨域响应头
app.use((req, res, next) => {
//设置请求头
res.set({
'Access-Control-Allow-Credentials': true,
'Access-Control-Max-Age': 1728000,
'Access-Control-Allow-Origin': req.headers.origin || '*',
'Access-Control-Allow-Headers': 'X-Requested-With,Content-Type',
'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS',
'Content-Type': 'application/text; charset=utf-8'
})
req.method === 'OPTIONS' ? res.status(204).end() : next()
});
app.post('/login', (req, res) => {
res.send(JSON.stringify(req.body));
});
app.listen(3000);