javascript – Using an authorization header with Fetch in React Native
javascript – Using an authorization header with Fetch in React Native
Example fetch with authorization header:
n
fetch(URL_GOES_HERE, { n method: post, n headers: new Headers({n Authorization: Basic +btoa(username:password), n Content-Type: application/x-www-form-urlencodedn }), n body: A=1&B=2n});n
‘
It turns out, I was using the fetch
method incorrectly.
n
fetch
expects two parameters: an endpoint to the API, and an optional object which can contain body and headers.
n
I was wrapping the intended object within a second object, which did not get me any desired result.
n
Heres how it looks on a high level:
n
fetch(API_ENDPOINT, OBJECT) n .then(function(res) {n return res.json();n })n .then(function(resJson) {n return resJson;n })n
n
I structured my object as such:
n
var obj = { n method: POST,n headers: {n Accept: application/json,n Content-Type: application/json,n Origin: ,n Host: api.producthunt.comn },n body: JSON.stringify({n client_id: (API KEY),n client_secret: (API SECRET),n grant_type: client_credentialsn })n}n
‘
javascript – Using an authorization header with Fetch in React Native
I had this identical problem, I was using django-rest-knox for authentication tokens. It turns out that nothing was wrong with my fetch method which looked like this:
n
...n let headers = {Content-Type: application/json};n if (token) {n headers[Authorization] = `Token ${token}`;n }n return fetch(/api/instruments/, {headers,})n .then(res => {n...n
n
I was running apache.
n
What solved this problem for me was changing WSGIPassAuthorization
to On
in wsgi.conf
.
n
I had a Django app deployed on AWS EC2, and I used Elastic Beanstalk to manage my application, so in the django.config
, I did this:
n
container_commands:n 01wsgipass:n command: echo WSGIPassAuthorization On >> ../wsgi.confn
Related posts on java script :
- Is JavaScript by reference or by value?
- What does parseFloat mean in JavaScript?
- How do you get the current URL with JavaScript?
- javascript – async.eachSeries in node.js
- javascript – Getting Unexpected Token Export
- javascript – How to connect signalR from angularJs
- javascript – Puppeteer wait until page is completely loaded
- How to validate email regex in JavaScript?
- javascript – Wait 5 seconds before executing next line
- javascript – Cannot Load m3u8: no EXTm3u delimiter JWPlayer Error