node.js 跨域接收請求和跨域返回
解決跨域接收請求
//設置跨域請求
app.all('*', function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By", ' 3.2.1')
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
解決跨域返回
// 使用中間件 允許跨域
// app.use(path,中間件函數)
app.use('/', (req, res, next) => {
// 注意, 需要帶 '*'
res.set('Access-Control-Allow-Origin', '*');
next();
});