Himmators Himmators - 6 months ago 22
Node.js Question

Can I pass a query with https.get in node.js?

I'm trying to pass a query in http.get.
This works:

https = require("https");

This results in a 404:

https = require("https");
host: 'graph.facebook.com',
path: '/v2.6/1109550759112324/accounts/test-users',
query: {
access_token: 'token'


There is no query option built into the HTTP or HTTPS library in Node Core when performing a request. Query strings are actually a separate module called querystring. Within that library there is the function stringify() which will take an object and create a query string from that, essentially in the fashion that you're expecting the https.get() to do for you in your question.

You can use querystring.stringify() with https.get() like so

const https = require('https');
const qs = require('querystring');

let query = qs.stringify({ access_token: 'token' });

    host: 'graph.facebook.com', 
    path: `/v2.6/1109550759112324/accounts/test-users?${query}`,    
}, (res) => {
    console.log(`StatusCode: ${res.statusCode}`);   
    let data = '';

    res.on('data', (chunk) => { data += chunk; });

    res.on('end', () => {
        // Parsing JSON response
        data = JSON.parse(data);

        console.log(`Body: ${JSON.stringify(data, null, 2)}`); 
}).on('error', (err) => {
    console.log(`Error: ${err}`);