node.js - 没有获得 req header 授权 token

标签 node.js react-native axios expo

我想使用 axios 将数据发送到我的后端。但 req.headers['Authorization'] 未定义。尽管我用 axios 发送它,但它不在 header 中。

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'
}

最佳答案

像这样发布您的请求

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)

关于node.js - 没有获得 req header 授权 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67401110/

相关文章:

javascript - 使用 npm 安装最新版本的包

mysql - 如何将 sequelize.sync 选项 force 设置为 false?

javascript - 在 native react 中使用带有地理定位的钩子(Hook)/状态我在哪里出错了?

javascript - Axios - 删除带有请求正文和 header 的请求?

javascript - 如何访问axios实例的baseURL

node.js - env 中的 RSA key 导致错误

node.js - 如何将 ThreeJS Collada 加载器与 TypeScript/Angular CLI 一起使用?

reactjs - 更新 : RCTView 管理的 View 的属性 'nativeBackgroundAndroid' 时出错

javascript - React Native,如何删除旧样式并添加新样式

Node.js Axios 请求