dont get req header authorization token

Viewed 280

I want to send Data with axios to my backend. But req.headers['Authorization'] is undefined. It is not in the header although I send it with axios.

axios:

import axios from 'axios';

const entryGroup = async (privatekey, userid) => {
  try {
    const options = {
      headers: {
        'Authorization': `Bearer ${userid}`,
        'Accept': 'application/json',
      },
      body: privatekey
    };

    return axios.post('http://xxxxx:3000/entrygroup', options).then(res => res.data).catch(e => e);
  } catch(e) {
    return e;
  }
};

export default entryGroup;

Nodejs: (all cors are enabled)

const dbf = require('../../functions/database/index');

module.exports = async (req, res) => {
  const { body } = req.body;
  console.log(req.headers);
  
};

Output from req.headers :

{
  accept: 'application/json, text/plain, */*',
  'content-type': 'application/json;charset=utf-8',
  'content-length': '127',
  host: 'xxxx:3000',
  connection: 'Keep-Alive',
  'accept-encoding': 'gzip',
  'user-agent': 'okhttp/3.14.9'
}
1 Answers

Post you request like this

import axios from "axios";

const entryGroup = async (privatekey, userid) => {
  try {
    return axios.post(
      "http://xxxxx:3000/entrygroup",
      { body: privatekey },
      {
        headers: {
          Authorization: `Bearer ${userid}`,
          Accept: "application/json",
        },
      }
    ).then(res => res.data).catch(e => e);
  } catch (e) {
    return e;
  }
};

export default entryGroup;

Then in backend You will get it in

console.log(req.headers)
Related