0

How can I send data with GET method using https/http module? With POST everything works.

First code (GET):

var querystring = require('querystring'),
    protocol = require('https');

var options = {
  host: 'httpbin.org',
  path: 'get',
  method: 'GET',
  headers: {},
  port: 443
};

var data = querystring.stringify({
  limit: 3
});

Object.assign(options.headers, {
  'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  'Content-Length': Buffer.byteLength(data)
});

var req = protocol.request(options, response => {
  response.setEncoding('utf8');
  var end = '';
  response.on('data', data => end += data);
  response.on('end', () => console.log(end));
});
req.write(data);
req.end();

Response:

{
  "args": {},
  "headers": {
    "Connection": "close",
    "Content-Length": "7",
    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
    "Host": "httpbin.org"
  },
  "origin": "31.0.120.218",
  "url": "https://httpbin.org/get"
}

Second code (POST, I only replaced options object):

var options = {
  host: 'httpbin.org',
  path: 'post',
  method: 'POST',
  headers: {},
  port: 443
};

Response:

{
  "args": {},
  "data": "",
  "files": {},
  "form": {
    "limit": "3"
  },
  "headers": {
    "Connection": "close",
    "Content-Length": "7",
    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
    "Host": "httpbin.org"
  },
  "json": null,
  "origin": "31.0.120.218",
  "url": "https://httpbin.org/post"
}

I will be very grateful for some help, now I don't know what I am doing wrong.

1
  • Not really a node.js issue. For GET, you do not post data in the body because it's not part of the http specification. The GET method is usually used for querying things. You send query parameters via the URL. Hope this helps. Commented Apr 11, 2017 at 19:59

1 Answer 1

2

Your problem is that in a get, the query is appended to the path, as @Quy points out, get requests don't have a body. Without an understanding of how the server is set up, I would look at doing it like so:

var data = querystring.stringify({
  limit: 3
});

var options = {
  host: 'httpbin.org',
  path: 'get?' + data,
  method: 'GET',
  headers: {},
  port: 443
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.