所有请求的Node.js静态头

时间:2015-03-15 09:07:40

标签: javascript node.js http http-headers

我想在node.js服务器中为所有传入请求设置静态标头。 我目前的方法是为每个请求添加相同的4行标题(代码重复),我想解决这个问题,这里是我要添加的标题的一个示例:

app.post('/postJob', function(req,res){
    console.log("request method :" + req.method);
    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', '*');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);
    res.setHeader('Content-Type', 'application/json');

有人知道定义它的方法吗?

1 个答案:

答案 0 :(得分:0)

喜欢这样

app.use(function(req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    res.setHeader('Access-Control-Allow-Credentials', true);
    res.setHeader('Content-Type', 'application/json');
    next();
});