javascriptreactjsauthenticationecmascript-6superagent

Bearer Authentication in React


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!


Solution

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