0

我正在使用 grunt-contrib-connect 在开发中为我的应用程序提供服务,升级到 node.js 0.12 后,我在尝试浏览我的应用程序时开始出错:

Error: "name" and "value" are required for setHeader().
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:333:11)
at ServerResponse.res.setHeader (/Users/abc/app/node_modules/grunt-contrib-connect/node_modules/connect/lib/patch.js:59:22)
at Object.module.exports.grunt.config.options.middleware.allowCors [as handle] (/Users/abc/app/grunt_tasks/connect.js:24:29)
at next (/Users/abc/app/node_modules/grunt-contrib-connect/node_modules/connect/lib/proto.js:190:15)
at Object.module.exports [as handle] (/Users/abc/app/node_modules/grunt-contrib-connect/node_modules/connect-livereload/index.js:84:5)
at next (/Users/abc/app/node_modules/grunt-contrib-connect/node_modules/connect/lib/proto.js:190:15)
at Function.app.handle (/Users/abc/app/node_modules/grunt-contrib-connect/node_modules/connect/lib/proto.js:198:3)
at Server.app (/Users/abc/app/node_modules/grunt-contrib-connect/node_modules/connect/lib/connect.js:65:37)
at Server.emit (events.js:110:17)
at HTTPParser.parserOnIncoming [as onIncoming] (_http_server.js:491:12)

除了升级节点外,没有其他任何变化。我尝试更新到最新版本的 grunt-contrib-connect,但我仍然收到错误消息。

4

1 回答 1

1

From the looking at the trace, it appears that the error is occurring in the middleware that is being specified to connect, in the function allowCors. It is common to have a middleware function specified to set CORS access headers on a response. As part of this function it is typical to have the line:

res.setHeader('Access-Control-Allow-Origin', req.headers.origin);

Which, as of node 0.12, will throw this error on requests where req.headers.origin is undefined.

It appears that in 0.12, a change was made that requires the value to exist, where previously it could be undefined. See the change: https://github.com/joyent/node/commit/979d0ca874df0383311ca06f154f6965074196ee

When using 0.12, when specifying this middleware function, one option would be simply add a check to see if req.headers.origin is defined before attempting to set the access headers on the response:

if (req.headers.origin) {
    res.setHeader('Access-Control-Allow-Credentials', true);
    res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
    res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version');
}
于 2015-03-19T18:37:20.077 回答