【问题标题】:Why I Can't get Auth header in Express?为什么我无法在 Express 中获取 Auth 标头?
【发布时间】:2019-04-03 13:46:17
【问题描述】:

我在axios 的帮助下从我的前端发送POST 请求,如下所示:

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

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

            })
            .catch(error => {

            })

在浏览器 console.log 中,我看到 headers 对象作为负载添加到请求中,而不是标头中。

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

这是我在 Express 中的 console.log:

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

我还使用 cors 库来处理 CORS(前端和后端的本地主机不同)

import cors from 'cors'

我做错了什么以及如何在 axios 的帮助下将身份验证添加到标题中?

【问题讨论】:

标签: javascript node.js express axios


【解决方案1】:

POST 的第二个参数是有效负载。第三个参数是标题。试试这个方法:

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

【讨论】:

  • 不客气,但我什至不知道 Axios 是什么 :) 这只是标准的 Node.js 语法。
  • 惊人的标准化 :) Axios 它是一个基于承诺的库,可以发送请求(GET POST 等)。
猜你喜欢
  • 2014-03-09
  • 1970-01-01
  • 2022-01-24
  • 2011-08-20
  • 2016-12-23
  • 1970-01-01
  • 1970-01-01
  • 2018-12-24
  • 2020-04-12
相关资源
最近更新 更多