【问题标题】:Node.js HTTP - TypeError: The header content contains invalid charactersNode.js HTTP - TypeError:标头内容包含无效字符
【发布时间】:2017-04-03 20:53:35
【问题描述】:
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();

我运行这段代码,我得到以下错误:

_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)

无法确定此错误的来源。我听说在较新版本的 Node 中是出于安全原因,但不知道如何绕过它。

【问题讨论】:

    标签: node.js http http-post nodejs-stream


    【解决方案1】:

    我有一个类似的问题,我正在为授权生成一个 jwt 令牌并且它正在插入换行符。用token.replace(/\r?\n|\r/g, '') 替换那些对我有用。

    【讨论】:

    • 哇,谢谢你,好先生!
    【解决方案2】:

    直截了当,看来我们需要使用:

     headers: {
        'content-type': 'application/json',
      },
    

    而不是

     headers: {
        'Content-Type': 'application/json',
      },
    

    这些类型的模糊错误信息让我很难过!

    【讨论】:

      【解决方案3】:

      这不是为什么。这是因为您的破折号 - 不是标准破折号:

      > /-/.test('cloudsso‐test.myco.com')
      false
      
      > /‐/.test('cloudsso‐test.myco.com')
      true
      

      【讨论】:

      • 有 3 个破折号 - emdash endash 和连字符
      【解决方案4】:

      我遇到了同样的错误信息。 结果 - 响应 cookie 标头包含 SOH ASCII command => \u0001:

      'set-cookie': [ 'someCookieName=rHA\u0001sBlP; path=/; Max-Age=900' ],
      

      所以我不得不重写每个标题​​:

      Object.entries(headers).forEach(([key, value]) => {
        delete headers[key];
        if (Array.isArray(value)) {
          headers[key] = value.map(v => v.replace(/[\x01]/g, ''));
        } else {
          headers[key] = value.replace(/[\x01]/g, '');
        }
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-24
        • 2023-02-05
        • 2016-10-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多