不获取请求头授权令牌

时间:2021-05-05 12:15:43

标签: node.js react-native axios expo

我想将带有 axios 的数据发送到我的后端。但是 req.headers['Authorization'] 是未定义的。虽然我用 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:(所有cors都启用)

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

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

来自 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 个答案:

答案 0 :(得分:1)

像这样发布您的请求

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;

然后在后端你会得到它

console.log(req.headers)