essxiv
essxiv

Reputation: 541

Node-Fetch API GET with Headers

https://www.npmjs.com/package/node-fetch Node v6.4.0 npm v3.10.3

I want to send a GET Request with custom headers in this API call.

const fetch = require('node-fetch')
var server = 'https://example.net/information_submitted/'

var loginInformation = {
    username: "[email protected]",
    password: "examplePassword",
    ApiKey: "0000-0000-00-000-0000-0"
}

var headers = {}
headers['This-Api-Header-Custom'] = {
    Username: loginInformation.username,
    Password: loginInformation.password,
    requiredApiKey: loginInformation.ApiKey
}

fetch(server, { method: 'GET', headers: headers})
.then((res) => {
    console.log(res)
    return res.json()
})
.then((json) => {
    console.log(json)
})

The headers are not applying, I am denied access. But within a curl command, it works perfectly.

Upvotes: 18

Views: 83752

Answers (2)

sillyslux
sillyslux

Reputation: 661

Let's use this bash command netcat -lp 8081 and change the url temporarily to http://localhost:8081/testurl. Now, the request will still fail, but our console shows some raw request data:

user@host:~$ netcat -lp 8081
GET /testurl HTTP/1.1
accept-encoding: gzip,deflate
user-agent: node-fetch/1.0 (+https://github.com/bitinn/node-fetch)
connection: close
accept: */*
Host: localhost:8081\r\n
\r\n

The two \r\n's are n fact invisible CRLFs, the spec says, these mark the end of headers and the beginning of the request body. You can see the extra new line in your console. Now if you rather want it to look like this:

user@host:~$ netcat -lp 8081
GET /testurl HTTP/1.1
username: [email protected]
password: examplePassword
requiredapikey: 0000-0000-00-000-0000-0
accept-encoding: gzip,deflate
user-agent: node-fetch/1.0 (+https://github.com/bitinn/node-fetch)
connection: close
accept: */*
Host: localhost:8081

then you only need a little change:

// var headers = {}
//headers['This-Api-Header-Custom'] = {
var headers = {
  Username: loginInformation.username,
  Password: loginInformation.password,
  requiredApiKey: loginInformation.ApiKey
}

fetch(server, { method: 'GET', headers: headers})

But if you want to set some special header This-Api-Header-Custom, then you can't pass in nested objects and arrays, but you have to serialize your data, i.e. turn username/password/requiredApiKey data into a string. Depending on your requirements, that might be e.g. CSV, JSON, ...

Upvotes: 13

newswim
newswim

Reputation: 450

I think you need to use the Headers constructor, instead of a plain object.

https://developer.mozilla.org/en-US/docs/Web/API/Headers

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Headers

myHeaders = new Headers({
  "Content-Type": "text/plain",
  "Content-Length": content.length.toString(),
  "X-Custom-Header": "ProcessThisImmediately",
});

Upvotes: 4

Related Questions