express 的跨域頭設置
先看代碼
var express = require('express');
var app = express();
//設置跨域訪問
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
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.get('/auth/:id/:password', function(req, res) {
res.send({id:req.params.id, name: req.params.password});
});
app.listen(3000);
console.log('Listening on port 3000...');
上面代碼主要主要是設置express所有的請求 `app.all(*, ...)` 這裏主要是攔截所有請求,並將請求頭設置爲 `允許跨域`, 尤其要注意的是,這類似於中間件操作,一定要記住 `next()`這個回調,將程序繼續執行。
PS: 這個似乎當初因爲項目需要,所以在segementfualt上尋找的一段代碼。在這裏感謝那位。