Stan
Stan

Reputation: 3

How to make a https reqest with Node.js? - My script produces TypeError in http.get

I try to make following curl request with node.js

curl \
  -H 'Authorization: ABC XYZ' \
  'https://api.wit.ai/message?q=Test'

(Authorization replaced)

I tried this node.js code:

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');
    });
});

However I always get this error:

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)

Thanks for any help!

Best regards

Stan

Upvotes: 0

Views: 156

Answers (1)

Aaron Dufour
Aaron Dufour

Reputation: 17535

From the http docs (anchor):

HTTP message headers are represented by an object like this:

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

You are passing headers as a String, which isn't parsing properly. Instead, you probably want:

headers: { Authorization: 'ABC XYZ' }

Upvotes: 2

Related Questions