Source:  Twitter logo

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!

rather than setting the full header with

.set({'Authorization': 'Bearer ' + this.state.id_token})

you can use

.auth(this.state.id_token, { type: 'bearer' })

4 users liked answer #0dislike answer #04
user2386601 profile pic
user2386601

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).

3 users liked answer #1dislike answer #13
Bilal profile pic
Bilal

Try using .auth('Bearer', this.state.id_token) http://visionmedia.github.io/superagent/#authentication

0 users liked answer #2dislike answer #20
Rikin profile pic
Rikin

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).