Himmators Himmators - 1 year ago 108
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'

Answer Source

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}`);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download