如何使用Node.js发出https请求? - Myscript在http.get中生成TypeError

时间:2014-03-30 18:22:28

标签: javascript node.js rest curl

我尝试使用node.js

进行以下curl请求
curl \
  -H 'Authorization: ABC XYZ' \
  'https://api.wit.ai/message?q=Test'

(授权更换)

我尝试了这个node.js代码:

var https = require("https");
var options = {
  hostname: 'https://api.wit.ai',
  port: 443,
  path: '/message?q='+phrase,
  headers: 'Authorization: ABC XYZ'
};
var request = https.get(options, function (response) {
    console.log("statusCode: ", response.statusCode);
    console.log("headers: ", response.headers);
    response.on('data', function(d) {
        console.info('GET result after POST:\n');
        process.stdout.write(d);
        console.info('\n\nCall completed');
    });
});

但是我总是遇到这个错误:

TypeError: Object.keys called on non-object
    at Function.keys (native)
    at new ClientRequest (http.js:1370:25)
    at Object.exports.request (https.js:123:10)
    at Object.exports.get (https.js:127:21)
    at analysePhrase (/home/vcap/app/app.js:33:21)
    at /home/vcap/app/app.js:70:2
    at callbacks (/home/vcap/app/node_modules/express/lib/router/index.js:161:37)
    at param (/home/vcap/app/node_modules/express/lib/router/index.js:135:11)
    at pass (/home/vcap/app/node_modules/express/lib/router/index.js:142:5)
    at Router._dispatch (/home/vcap/app/node_modules/express/lib/router/index.js:170:5)

感谢您的帮助!

祝你好运

斯坦

1 个答案:

答案 0 :(得分:2)

来自http docs(anchor):

  

HTTP消息头由如下对象表示:

{ 'content-length': '123',
  'content-type': 'text/plain',
  'connection': 'keep-alive',
  'accept': '*/*' }

您将标题作为String传递,但未正确解析。相反,你可能想要:

headers: { Authorization: 'ABC XYZ' }