标签:use next put 配置 product ext 实现 add key
1. 不用中间件的话可以这样写
app.all(‘*‘, function (req, res, next) { res.header("Access-Control-Allow-Origin", "http://www.xxx.com");
res.header(‘Access-Control-Allow-Credentials: true‘); //是否支持cookie跨域
res.header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By",‘ 3.2.1‘) if(req.method=="OPTIONS")
res.send(200);/*让options请求快速返回*/ else next();
})
2. 使用CORS,和其他中间件的用法一样,app.use()即可:
var express = require(‘express‘) var cors = require(‘cors‘) var app = express() app.use(cors())
3.如果要单独为某个接口实现允许跨域请求,在回调函数之前先用cors()方法进行跨域处理即可:
var express = require(‘express‘) var cors = require(‘cors‘) var app = express() app.get(‘/products/:id‘, cors(), function (req, res, next) { res.json({msg: ‘This is CORS-enabled for a Single Route‘}) })
4.手动配置
app.use(cors({
origin:[‘http://localhost:8080‘],//允许该域名下的请求
methods:["GET","POST"], // 允许接受的 请求类型
alloweHeaders:[‘Conten-Type‘,‘Authorization‘,‘Accept‘,‘Origin‘], //请求头
exposeHeaders: [‘WWW-Authenticate‘, ‘Server-Authorization‘],
credentials: true, // 发送cookie
}));
前端用axios
,需要设置一下cookie
axios.defaults.withCredentials = true // axios请求携带cookie
this.$axios({ xhrFields:{ withCredentials: true },//axios设置携带cookie method: ‘post‘, url: ‘http://localhost:3000/admin/add‘, data: param }) .then((response)=>{ console.log("sd"); console.log(response.data.results); }) .catch((err)=>{ console.log("失败?"); console.log(err); })
cors跨域(支持cookie跨域) node后台 express
标签:use next put 配置 product ext 实现 add key
原文地址:https://www.cnblogs.com/caoleyun/p/12848433.html