Different headers for post and get request with axios,create? - javascript

export default myAPI = axios.create({
baseURL: 'myapiurl',
// headers for post reuqest
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Accept: 'application/json',
'X-CSRF-TOKEN': 'o987WyyzM7ktyEVzP4dakCdIY12LprtJU8qZHs5Xs0s',
},
// headers for get requests
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
});
Basically want conditional headers depending on weather a post or a get request is being made.

You can use different headers based on HTTP method in this way:
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
As explained here: https://github.com/axios/axios#global-axios-defaults

Related

React how to get accessToken?

I want to send a post with fetching. But I get 401 error: www-authenticate: Bearer error="invalid_token".
I am using Userfront.accessToken() but It did not work.
How can I get accestoken for bearer authentication?
const submit = (e) => {
e.preventDefault();
const data = new FormData(form.current);
fetch(process.env.REACT_APP_ENDPOINT + "user/me/contract", {
method: "POST",
body: data,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${Userfront.accessToken()}`,
},
}).then((res) => res.json());
};
Note:
console.log(`Bearer ${Userfront.accessToken()}`);
Bearer [object Object]
Can you try this? I see this from https://userfront.com/guide/auth/
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${Userfront.tokens.accessToken}`
}
JSON.stringify(Userfront.accessToken()) please stringify that object to understand what is going on there then if there is accessToken returning from that function put that string.
I just realized in the doc;
To handle a request like this -Userfront.accessToken()-, your backend should read the JWT from
the Authorization header and verify that it is valid using the public
key found in your Userfront dashboard.
https://userfront.com/guide/auth/
fetch('https://api.example.com', {
method: 'GET'
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${Userfront.tokens.accessToken}`
}
});
Thank you all for your answers.
Authorization: `Bearer ${localStorage.getItem("fray_access_token")}`,
In this application, token gets a different name.
When I look from inspects, I use it and it works!

Content-type from fetch in locally run React code

I am new to front end dev. How can I set "application/json" content-type and gzip content-encoding in the fetch call in locally run React code?
const data = await fetch(url, {
method: 'post',
body: body,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json' // this does not work when run locally
}
});
You could try this
const data = await fetch(url, {
method: 'post',
body: JSON.stringify(body), // this will encode body to string, assuming it's an Object
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
});
but I'm not sure what do you want with "gzip content-encoding". If the console prints any errors, they can be helpful too

how to handle request header accept application/ld+json in react.js get request

how to handle request header accept application/ld+json in react.js get request
Media type
application/id+json
Controls Accept header.
i am getting unauthorized 401 error dont know why can anyone please explain me i am facing this type of error for the first time .
function parseJwt(token) {
if (!token) { return; }
const base64Url = token.split('.')[1];
const base64 = base64Url.replace('-', '+').replace('_', '/');
return JSON.parse(window.atob(base64));
}
export async function getRequest(url , token){
let token_data = parseJwt(token)
console.log('Token data ', token_data)
let response = await fetch(API_URL(url), {
method: "GET",
mode: "cors",
cache: "no-cache",
credentials: "same-origin",
headers: {
"Accept": `application/${token_data.id}+json`,
// 'Content-Type': `application/${token_data.id}+json`,
// "Authorization": JSON.stringify(token_data)
},
redirect: "follow",
referrer: "no-referrer",
})
return response
}
Please Try Below code
var token = 'XXXXX-XXXX-XXXXX';
const response = await fetch(url, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'Authorization': token
},
body: payLoad,
})

How to send HTTP headers in ReactJS using fetch()

const URL = "http://url.com";
fetch(URL).then(res => res.json()).then(json => {
this.setState({ someData: json });
});
How to send HTTP request with HTTP headers?
Try this
fetch('your_url', {
method: 'get',
headers: new Headers({
// Your header content
})
});
You can just pass them into fetch():
const API = 'foo';
fetch(API, { headers: {
'user-agent': 'Mozilla/4.0 MDN Example',
'content-type': 'application/json'
}}).then()
You can read more on that here.
Inside the fetch() method you should do something like this
fetch(url, {
...
headers: {
'user-agent': 'Mozilla/4.0 MDN Example',
'content-type': 'application/json'
}
For more details, look at the Mozilla Developers documentation.

fetch doesn't set headers in chrome

I try to get a POST request working via the fetch() function. The problem is that my headers won't be set and the request fails.
Here is an example code of my request:
fetch('https://google.com', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-FOO-BAR': 'bla'
},
mode: "no-cors",
body: JSON.stringify({
data: "here"
})
});
My main problem is, that the Content-Type will be set to text/plain, which is why my request fails. I added the X-FOO-BAR header just to see if it gets set. But it won't get set.

Categories

Resources