Node.js的HTTP - 类型错误:标题内容包含无效字符
问题描述:
const http = require('http');
const req = http.request({
method: 'POST',
hostname: 'cloudsso‐test.myco.com',
port: 80,
path: '/as/token.oauth2',
headers: {
'Content-Type': 'application/json',
},
agent: false // create a new agent just for this one request
}, function (res) {
res.on('headers', function (h) {
console.log('headers => ', h);
});
let data = '';
res.on('data', function (d) {
data += d;
});
res.once('end', function() {
console.log('data => ', data);
});
});
req.write(JSON.stringify({
client_id: 'xxx',
client_secret: 'secret',
grant_type: 'refresh_token',
}));
req.end();
我运行此代码,我得到以下错误:Node.js的HTTP - 类型错误:标题内容包含无效字符
_http_outgoing.js:358
throw new TypeError('The header content contains invalid characters');
^
TypeError: The header content contains invalid characters
at ClientRequest.OutgoingMessage.setHeader (_http_outgoing.js:358:11)
at new ClientRequest (_http_client.js:105:12)
at Object.exports.request (http.js:31:10)
at Object.<anonymous> (/Users/alexamil/WebstormProjects/cisco/cdt-now/test/refresh-token.js:9:18)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
无法揣摩出这个错误的来源。我听说这是出于安全的原因在较新版本的节点,但无法弄清楚如何绕过它。
答
直线上升,看起来,我们需要使用:的
headers: {
'content-type': 'application/json',
},
代替
headers: {
'Content-Type': 'application/json',
},
这些类型的模糊的错误消息让我伤心!
答
我有一个类似的问题,我为授权生成一个jwt令牌,它插入换行符。用token.replace(/\r?\n|\r/g, '')
代替那些对我来说是诀窍。