OberDulli94
OberDulli94

Reputation: 187

HTTPS with NodeJS set request headers

Hey guys I'm struggling a little bit with Node JS and HTTPS requests. The following code actually works fine but I don't know how to set custom request headers like X-Forwarded-For and User Agent. Is there a way to add these?

Thanks :)

Here is my code:

    const https = require('https');

const options = {
  hostname: 'offertoro.com',
  port: 443,
  path: '/',
  method: 'GET'
};

const req = https.request(options, (res) => {

  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });
});

req.on('error', (e) => {
  console.error(e);
});
req.end();

Upvotes: 8

Views: 9176

Answers (2)

Marcos Casagrande
Marcos Casagrande

Reputation: 40404

options argument accepts a headers property.

const options = {
  hostname: 'offertoro.com',
  port: 443,
  path: '/',
  method: 'GET',
  headers: {
     'X-Forwarded-For': 'xxx',
     'User-Agent': 'Foo'
  }
};

Upvotes: 12

Lint
Lint

Reputation: 935

I think you're talking about response headers not request headers, because request headers are that are sent to you in a request body, you receive them not you set them Rather you set response headers, which are you be sent when you respond with any action If that's the case, you can set response header by

res.header('headersName','headersVALUE')

Upvotes: 0

Related Questions