0
votes

I send the POST request from my frontend with help of axios like this:

const headers =  {
            headers: {
                'Authorization': `Bearer ${localStorage.token}`,
            }
        }

API.post('validate', headers )
            .then(res => {

            })
            .catch(error => {

            })

In browser console.log I see that headers object was added as payload to request, not to headers.

router.post('/', errorHandler(async (req, res, next) => {
    console.log(req.method)
    console.log(req.headers)
    let bearerHeader = req.headers['Authorization']
    console.log(bearerHeader)
})

This is my console.log in Express:

POST
{ host: 'localhost:5000',
  connection: 'keep-alive',
  'content-length': '244',
  accept: 'application/json, text/plain, */*',
  origin: 'http://localhost:3000',
  'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
  'content-type': 'application/json;charset=UTF-8',
  referer: 'http://localhost:3000/signin',
  'accept-encoding': 'gzip, deflate, br',
  'accept-language': 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7,uk;q=0.6' }
undefined

Also I use cors library to work with CORS (different localhost for frontend and backend)

import cors from 'cors'

What am I doing wrong and how actually add auth to header with help of axios?

1
Have you tried making it your authorization header on the axios default object? github.com/axios/axios#global-axios-defaultstechnogeek1995

1 Answers

4
votes

POST's second argument is the payload. The third argument is the headers. Try this way :

API.post('validate', {}, headers )