Node fetch authorization header

Node fetch authorization header DEFAULT

Fetch sending Authorization header in one but not the other?

Hi there,

I’m really inexperienced with APIs hope you can help me out.

I’m using Fetch to reach my endpoints. Had a previous problem with setting the ‘Content-Type’ request header giving my a weird 404 response. Anyways i removed that Content-Type header and then it was working.

Now i want to like ‘conform’ to standards and place my token in the Authorization header, but its happening again! One endpoint can receive the Authorization header and i can do my checking and its good, the other doesn’t even receive it!


Not working:

Btw when i test them on the dev server its all working fine, but when i put it on the production server, one endpoint works the other doesnt. They are both in the same controller! (this is CodeIgniter btw)

I’ve tried using Postman to proxy and listen to traffic, but as i am so inexperienced when i set the proxy i can surf the internet from my mobile but on the app/expo logs it just keeps saying ‘Network request failed’, so i can’t see anything.

Anyone help me out here? (with any of my problems above)


Best JavaScript code snippets using node-fetch(Showing top 15 results out of 1,926)

function sendRequest (opts) { const options = { headers: { 'User-Agent': ' release blog post script' }, ...opts } returnfetch(options.url, options).then(resp => { if (resp.status !== 200) { thrownew Error(`Invalid status code (!= 200) while retrieving ${options.url}: ${resp.status}`) } return options.json ? resp.json() : resp.text() }) }
async manifestJSON() { const response = awaitfetch( `${this.repo.owner}/${}/contents/manifest.json` ); return JSON.parse(Buffer.from((await response.json()).content, 'base64').toString()); }
const processJob = async () => { debug('pinging compose to start on-demand db backup'); const result = await compose( `2016-07/deployments/${COMPOSE_DEPLOYMENT_ID}/backups`, { method: 'POST', } ); const json = await result.json(); debug(json); return; }
async downloadRepo() { const url = `${this.repo.owner}/${}/archive/master.tar.gz`; const writer = fs.createWriteStream(this.repoArchivePath); (awaitfetch(url)).body.pipe(writer); returnnew Promise((resolve, reject) => { writer.on('finish', resolve); writer.on('error', reject); }); }
function callAPI({ path, method, data }) { const ROOT_URI = `https://${process.env.MAILCHIMP_REGION}`; returnfetch(`${ROOT_URI}${path}`, { method, headers: { Accept: 'application/json', Authorization: `Basic ${Buffer.from(`apikey:${process.env.MAILCHIMP_API_KEY}`).toString( 'base64', )}`, }, body: JSON.stringify(data), }); }
exportdefaultfunction fetchBrasilAPIService (cepWithLeftPad) { const url = `${cepWithLeftPad}` const options = { method: 'GET', mode: 'cors', headers: { 'content-type': 'application/json;charset=utf-8' } } returnfetch(url, options) .then(parseResponse) .then(extractCepValuesFromResponse) .catch(throwApplicationError) }
const compose = (path: string, fetchOptions?: Object = {}) => { if (!COMPOSE_API_TOKEN) { thrownew Error('Please specify the COMPOSE_API_TOKEN env var.'); } returnfetch(`${path}`, { ...fetchOptions, headers: { 'Content-Type': 'application/json', ...(fetchOptions.headers || {}), Authorization: `Bearer ${COMPOSE_API_TOKEN}`, }, }); }
exportdefaultasyncfunction fetch() { const res = => { return fetch(...args).then(res => { const { url, status, headers } = res; return res.text().then(body => { return { url, status, body, headers }; }); }); }, ...arguments); returnnew Response(res.body, res); }
const fetchStory = async (storyId) => { return (awaitfetch(`${storyId}.json`)).json(); }
exportdefaultfunction fetchCorreiosService (cepWithLeftPad, proxyURL = '') { const url = `${proxyURL}` const options = { method: 'POST', body: `<?xml version="1.0"?>\n<soapenv:Envelope xmlns:soapenv="" xmlns:cli="">\n <soapenv:Header />\n <soapenv:Body>\n <cli:consultaCEP>\n <cep>${cepWithLeftPad}</cep>\n </cli:consultaCEP>\n </soapenv:Body>\n</soapenv:Envelope>`, headers: { 'Content-Type': 'text/xml;charset=UTF-8', 'cache-control': 'no-cache' } } returnfetch(url, options) .then(analyzeAndParseResponse) .catch(throwApplicationError) }
exportdefaultfunction fetchViaCepService (cepWithLeftPad, proxyURL = '') { const url = `${proxyURL}${cepWithLeftPad}/json/` const options = { method: 'GET', mode: 'cors', headers: { 'content-type': 'application/json;charset=utf-8' } } returnfetch(url, options) .then(analyzeAndParseResponse) .then(checkForViaCepError) .then(extractCepValuesFromResponse) .catch(throwApplicationError) }
function callAPI({ path, method, data }) { const ROOT_URI = `https://${process.env.MAILCHIMP_REGION}`; returnfetch(`${ROOT_URI}${path}`, { method, headers: { Accept: 'application/json', Authorization: `Basic ${Buffer.from(`apikey:${process.env.MAILCHIMP_API_KEY}`).toString( 'base64', )}`, }, body: JSON.stringify(data), }); }
const fetchUser = async (userId) => { return (awaitfetch(`${userId}.json`)).json(); }
exportdefaultfunction fetchWideNetService (cepWithLeftPad, proxyURL = '') { const url = `${proxyURL}${cepWithLeftPad}.json` const options = { method: 'GET', mode: 'cors', headers: { 'content-type': 'application/json;charset=utf-8' } } returnfetch(url, options) .then(analyzeAndParseResponse) .then(checkForWideNetError) .then(extractCepValuesFromResponse) .catch(throwApplicationError) }
  1. Treasure planet cast
  2. Granite stone blue
  3. Cat c15 generator
  4. 30 tv best buy
  5. Free agents nba 2021 list

React + Fetch - Set Authorization Header for API Requests if User Logged In

This is a quick example of how to automatically set the HTTP header for requests sent with from React to an API when the user is authenticated.

The code snippets in this tutorial are from a React + Recoil JWT Auth tutorial I posted recently, to see the code running in a live demo app check out React + Recoil - JWT Authentication Tutorial & Example.

Recoil is used in the example to store the current authenticated user in the shared state object, but Recoil isn't required if your React app uses another way to store the user's logged in state such as Redux or RxJS etc. The only requirement is that you can check if the user is logged in from the function in the fetch wrapper below.


Fetch Wrapper with Set Authorization Header

Path: /src/_helpers/fetch-wrapper.js

The fetch wrapper is a lightweight wrapper around the native browser function used to simplify the code for making HTTP requests by automatically setting the HTTP auth header, parsing JSON response data and handling errors. It returns an object with methods for , , and requests.

The function is used to automatically add a JWT auth token to the HTTP header of the request if the user is logged in and the request is to the application API url ().

With the fetch wrapper a request can be made as simply as this: . It's called in the example app by user actions for login and to fetch all users.


User Actions

Path: /src/_actions/user.actions.js

The user actions object returned by the hook function contains methods for login, logout and fetching all users. It handles communication between the React app and the backend api for everything related to users, and also handles Recoil state update operations for users and auth atoms. HTTP requests to the API are sent with the fetch wrapper.

The method is called from a secure page in the React example app after the user has logged in, so the fetch wrapper automatically sets the HTTP header of the request to the JWT token of the authenticated user.

The method is called from the public login page when the user is not yet logged in, so the function of the fetch wrappper doesn't set the authorization header of the request.


Subscribe to my YouTube channel or follow me on Twitter, Facebook or GitHub to be notified when I post new content.

I'm currently attempting to travel around Australia by motorcycle with my wife Tina on a pair of Royal Enfield Himalayans. You can follow our adventures on YouTube, Instagram and Facebook.

Need Some React Help?

Search fiverr to find help quickly from experienced React developers.

I'm currently attempting to travel around Australia by motorcycle with my wife Tina on a pair of Royal Enfield Himalayans. You can follow our adventures on YouTube, Instagram and Facebook.

Need Some React Help?

Search fiverr to find help quickly from experienced React developers.

Learn Fetch API In 6 Minutes

Knowledge center

Hi all,

I am trying to get all subscriptions using fetch. Here is my code:

const url = 'https://[mywebsite]';

const username = [mysecrectkey];



       headers: {'Authorization': 'Basic '+btoa(username)}



        return res.json();


      .then(function(data) {



But I get the error message like this:

Failed to load resource: the server responded with a status of 405 (Method Not Allowed)

Failed to load https://*** Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '' is therefore not allowed access. The response had HTTP status code 405. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Uncaught (in promise) TypeError: Failed to fetch

anyone knows how to code it the right way? Thanks...


Header node fetch authorization

Using an authorization header with Fetch in React Native

I'm trying to use in React Native to grab information from the Product Hunt API. I've obtained the proper Access Token and have saved it to State, but don't seem to be able to pass it along within the Authorization header for a GET request.

Here's what I have so far:

The expectation I have for my code is the following:

  1. First, I will an access token with data from my imported API module
  2. After that, I will set the property of to equal the access token received.
  3. Then, I will run which should return a response containing an array of current posts from Product Hunt.

I am able to verify that the access token is being received and that is receiving it as its property. I am also able to verify that is being run.

The error I'm receiving is the following:

{"error":"unauthorized_oauth", "error_description":"Please supply a valid access token. Refer to our api documentation about how to authorize an api request. Please also make sure you require the correct scopes. Eg \"private public\" for to access private endpoints."}

I've been working off the assumption that I'm somehow not passing along the access token properly in my authorization header, but don't seem to be able to figure out exactly why.

How to Use Window Fetch API in Node.js App Using node-fetch Module Full Example

Javascript Fetch


We'll use and describe the problems that it helps solve.


  1. Explain how to use in modern browsers
  2. Describe the differences between , and
  3. Get data from a remote endpoint using


Getting remote data in JavaScript has classically required a fair amount of plumbing to make things happen.

It's not that it's hard to get data out of , but it does take quite a bit of setup. Let's make a simple request of the GitHub repository commits API.

Sure, it works, but that's a lot of setup to just say "give me some JSON from this URL".

I mean, you could just crack an egg and start cooking it, you know? Similarly, I'll never understand why we have to call and then call . Or why we can only set headers after we call . Or any number of other clunky ways we have to use XHR.

Things get a little better with jQuery's , except then we have to tightly couple ourselves to jQuery, and ultimately, it's just syntactic sugar over .

XHR also abstracts away our ability to work directly with the request and response objects, limiting our ability to do more advanced things on an internet that's evolved far beyond just XML and HTTP.

Note: To be fair to XHR, it can handle more protocols than HTTP and more formats than XML, but it was never designed with the level of interconnectedness of today's programs in mind. For instance, streaming, a staple of the modern web, isn't possible when you can only access after the request has completed.

Wouldn't it be nice if there were a sleek new API designed from the ground up to handle the needs of the modern web?


The function is a new API for fetching resources. It's a global function, which means no creating new XHR objects, and it vastly streamlines simple resource requests. Let's try that call to the GitHub commits API again.

kimmy wow

I know, right? Let's break it down.

Since we're making a simple request, we can just pass the URL directly to . But what's happening next?

Promises and then

In JavaScript, a object represents a value that may not be available yet, but will be resolved at some point in the future. Essentially, the promise is an object that represents the result of an operation, whenever it occurs. This allows us to write more flexible asynchronous code than simply passing callback functions to asynchronous functions.

All promises implement a function that is called when the promise is fulfilled, or completed successfully. So this is very similar to the idea of a callback on success that we'd use with or .

The interesting thing about this code is that it highlights a powerful feature of a object — we can chain each call, and the next one receives the result of the previous one as its argument.

So, in this code:

the line is getting the response from and using the method (more on this in a bit) to turn it into JSON. Then it's passing the JSON to the next line, , to be handled by that function.

Body Mixin

The API includes a mixin, or additional code, called Body, which has functions that specialize in transforming the of a request or response.

In an , you would potentially have to the data to turn it into JSON. The mixin takes that a step further, giving us handy ways to parse many formats, including JSON, plain text, and even blobs for binary or image data.

So calling in our is just a nice shorthand for saying "give me the of the response parsed as JSON".

Authenticated Fetching

So far, we've been making our requests against the public API functions that GitHub provides, but there are more powerful toys available to us if we can prove to the API who we are when we make requests.


GitHub's API uses OAuth2 for authorization. In a production setting, you would register an application with GitHub and receive an application ID and secret. This allows GitHub to track and monitor API access, and ensure that its users are protected by only granting authorization through registered apps.

From there, a user would make a request via your app, which would kick off the workflow to issue an authorization code that your app would then exchange for an access token. The access token is ultimately what your application includes in GitHub API requests to identify and authorize the user.

Setting up the full OAuth2 authorization code grant workflow is beyond the scope of this lesson, but it is described well in the GitHub docs.

Fortunately for us, GitHub also allows you to generate your own personal authorization token that we can use to give us authorized access to the API. And makes it super easy to implement.

To start, go to and click "Generate new token." Name it "" and check scope. Once you generate the token, make sure to copy and paste it somewhere, because once you leave that page, you won't be able to see it again. This is for your security — even if someone were to gain access to this page on your account, they still couldn't see your tokens.

Using the token to access the API is a simple matter of creating an header with our request. Let's try it out by listing our repos.

If we run that code, we'll get a response. We need to provide our authorization token in order to list our own repositories with this API, so let's add our header (don't forget to assign your token to ).

We just pass the desired headers as part of a second options argument to and we are in business. Easy as that!

so fetch

Top-Tip: Don't ever give out your access token or store it in a publicly accessible place or a shared GitHub repository. We're just using these for learning purposes. In a production setting, users' access tokens would be stored securely in a database and not exposed to other people.


View Getting Data from the Web on and start learning to code for free.


You will also be interested:


2121 2122 2123 2124 2125