Bearer Authentication in React
13,953
Solution 1
The way headers are set is by providing the header item name and value, try:
showTransactionList = () => {
superagent
.post('http://193.124.114.46:3001/api/protected/transactions')
.set('Authorization', 'Bearer ' + this.state.id_token)
.accept('application/json')
.then(res => {
const posts = JSON.stringify(res.body);
console.log(posts);
})
.catch((err) => {
console.log(err);
throw err;
});
}
So instead of setting the object in the header, pass it as 2 parameters (name, value).
Solution 2
rather than setting the full header with
.set({'Authorization': 'Bearer ' + this.state.id_token})
you can use
.auth(this.state.id_token, { type: 'bearer' })
Author by
Andrew Fleyer
Updated on June 04, 2022Comments
-
Andrew Fleyer almost 2 years
How can I use Bearer Authentication with superagent in React? I am not sure in syntax and can't find an example.
What I do now
showTransactionList = () => { superagent .post('http://193.124.114.46:3001/api/protected/transactions') .set({'Authorization': 'Bearer ' + this.state.id_token}) .accept('application/json') .then(res => { const posts = JSON.stringify(res.body); console.log(posts); }) .catch((err) => { console.log(err); throw err; }); }
Thnx!
-
Andrew Fleyer over 5 yearsno. it doesn't help. response the same Error: "Unauthorized"
-
Rikin over 5 yearsAre you able to see any Auth being added in the HTTP request in console or possibly any proxy?
-
Andrew Fleyer over 5 yearsThe same result.
-
Bilal over 5 yearsThen probably you should use the (superagent-auth-bearer) plugin which is provided for this purpose npmjs.com/package/superagent-auth-bearer
-
Andrew Fleyer over 5 yearssending SET not like a single object was useful. Thanks