Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node-Fetch API GET with Headers

Tags:

node.js

api

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.

like image 536
essxiv Avatar asked Oct 18 '16 04:10

essxiv


People also ask

How do I get response headers in Fetch?

You can't directly access the headers on the response to a fetch call – you have to iterate through after using the entries() method on the headers. Code sample (using react and looking for a query count) below: fetch(`/events? q=${query}&_page=${page}`) .

What are headers in a fetch request?

The Headers interface of the Fetch API allows you to perform various actions on HTTP request and response headers. These actions include retrieving, setting, adding to, and removing headers from the list of the request's headers.

Can you use fetch API in NodeJS?

Fetch() support is now available in Node. js as an experimental core feature. Fetch() is a well-liked cross-platform HTTP client API that functions in browsers and Web/Service Workers.

How do you get a response body in node-fetch?

The code that follows serves as an illustration of this point. const fetch = require('node-fetch'); //npm install node-fetch fetch('https://httpbin.org/post', { method: 'POST', body: 'a=1' }) . then(res => res. json()) .


1 Answers

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",
});
like image 138
newswim Avatar answered Sep 18 '22 22:09

newswim