Sergio Casolari
Sergio Casolari

Reputation: 19

How to pass Authorization token from ReactJS to NodeJS request

I'm try to pass the 'token_mailchimp' from axios get request to nodejs request get

For the moment i pass the auth token from a variable directly in app.js in my node/express project.

app.js in node/express project

app.get('/mailchimp/campaigns', checkAuth, function (req, res) {
    request
        .get('https://' + mailchimpInstance + '.api.mailchimp.com/3.0/campaigns')
        .set('Content-Type', 'application/json;charset=utf-8')
        .set('Authorization', 'Basic '+token_mailchimp)
        .end((err, result) => {
            if (err) {
                res.status(500).json(err);
            } else {
                res.json(result.body);
            }
        });
});

axios get request in ReactJS project

.get('http://localhost:8081/mailchimp/campaigns',
                { headers: {"Authorization" : `Bearer `+jwt_token} })
            .then(({ data })=> {
                this.setState({
                    campaigns: data.campaigns
                });
            })
            .catch((err)=> {})

How can i pass from axios request the auth token for the request /mailchimp/campaigns?

Upvotes: 1

Views: 1192

Answers (1)

Amol B Jamkar
Amol B Jamkar

Reputation: 1257

You can send a new custom header like x-api-token

{ headers: {"Authorization" : Bearer+jwt_token, "x-api-token" : "your_token"} }

Then in the app.js, access the headers from the request,

const {headers} = req;

Then use that in your API request

.set('Authorization',`Basic ${headers["x-api-token"]}`)

Note: If you are using cors plugin then make sure it's allowing that header to pass. You can add header x-api-token manually in cors configuration if needed.

Upvotes: 2

Related Questions