【问题标题】:dont get req header authorization token不获取 req 标头授权令牌
【发布时间】:2021-07-27 18:21:09
【问题描述】:

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

【问题讨论】:

    标签: node.js react-native axios expo


    【解决方案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)
    

    【讨论】:

    • 你的身体正确吗?我的意思是你在 Node.js 中得到 privatekey 吗??
    • 你在使用 Express 吗??
    • 是的,我使用 express 并且正确获取了正文
    • 我向你展示我的 req.headers 输出我在上面编辑了我的代码
    • 很高兴帮助队友!
    猜你喜欢
    • 2015-05-26
    • 2017-11-06
    • 1970-01-01
    • 2016-11-29
    • 2021-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多