【问题标题】:How to pass authorization token in header to react Axios.post?如何在标头中传递授权令牌以响应 Axios.post?
【发布时间】:2020-07-03 19:42:18
【问题描述】:

我使用 React、Express、MongoDB 的应用程序。

我想为 Axios 发布请求传递带有标头的身份验证令牌。

但是,当我试图通过它时,得到 403 错误(禁止)。

本地存储

我正在从本地存储中检索所有身份验证数据

export function authHeader() {
    // return authorization header with basic auth credentials
    let user = JSON.parse(localStorage.getItem('user'));

    if (user && user.token) {
        return { Authorization: `Bearer ${user.token}` };
    } else {
        return {};
    }
}

Axios.post

我在这里调用 axios post 请求

import React, { Component } from 'react'
import Axios from 'axios';
import { authHeader } from '../../../helpers'

export default class SubAdmin extends Component {
    constructor(props) {
        super(props)

        this.state = {
            user: {},
            users: [],
            error: null,
            isLoaded: false,
            items: []
        }
    };

    componentDidMount() {
        this.setState({
            user: JSON.parse(localStorage.getItem('user')),
            users: { loading: true }
        });
        Axios.post('http://localhost:4200/api/viewSubAdmin', 
                    {
                        headers: authHeader()
                    }).then(
          result => {
              console.log(result);

            this.setState({
              isLoaded: true,
              items: result.data
            });
          },
          error => {
            this.setState({
              isLoaded: true,
              error
            });
          }
          );
      }

API 标头和响应

这是我从浏览器得到的响应

Request URL: http://localhost:4200/api/viewSubAdmin
Request Method: POST
Status Code: 403 Forbidden
Remote Address: [::1]:4200
Referrer Policy: no-referrer-when-downgrade
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 9
Content-Type: text/plain; charset=utf-8
Date: Mon, 23 Mar 2020 10:04:33 GMT
ETag: W/"9-PatfYBLj4Um1qTm5zrukoLhNyPU"
X-Powered-By: Express
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 171
Content-Type: application/json;charset=UTF-8
Host: localhost:4200
Origin: http://localhost:3000
Referer: http://localhost:3000/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36
{headers: {,…}}
headers: {,…}
Authorization: "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhZG1pbiI6IjEyMzQ1Njc4OSIsImlhdCI6MTU4NDk1MDM3MH0.Bk4q3qEsVrA8TDn7Bbk5M689B-6uVfg4r9FTmfDTWc4"

我的邮递员电话工作正常

POST: http://localhost:4200/api/viewSubAdmin
Headers: Authorization:"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhZG1pbiI6IjEyMzQ1Njc4OSIsImlhdCI6MTU4NDk1MDM3MH0.Bk4q3qEsVrA8TDn7Bbk5M689B-6uVfg4r9FTmfDTWc4",
Response Body: {
    "subadmin_details": [
        [
            {
                "isBlocked": false,
                "_id": "5e5749872eb4ab0ff5c037f9",
                "name": "abcd",
                "password": "123456",
                "admintype": "subadmin"
            },
            {
                "isBlocked": false,
                "_id": "5e574b4a2eb4ab0ff5c037fb",
                "name": "abcde",
                "password": "123456",
                "admintype": "subadmin"
            },
            {
                "isBlocked": false,
                "_id": "5e57c2b7fe57bc7a7165cd64",
                "name": "12345678",
                "password": "12345678",
                "admintype": "subadmin",
                "__v": 0
            },
            {
                "isBlocked": false,
                "_id": "5e57c31594c9287afdf186f9",
                "name": "1234567",
                "password": "1234567",
                "admintype": "subadmin",
                "__v": 0
            },
            {
                "isBlocked": false,
                "_id": "5e57c3266dfbde7b1507453a",
                "name": "123456",
                "password": "123456",
                "admintype": "subadmin",
                "__v": 0
            }
        ]
    ]
}

【问题讨论】:

  • 我不确定这是否可行,但您可以尝试一次。你可以在你的axios post-call中做标题:() => authHeader()。
  • 不工作,顺便说一句,感谢您分享您的想法
  • 我看到了邮递员的回复,并与您的本地请求进行了比较。我认为 Headers 中的 H 在 postman 中是大写,但在您的本地则很小。
  • 我也试过了,但没有改变

标签: reactjs rest api post axios


【解决方案1】:

Axios.post 按顺序接收urldataheaders 作为参数。如果只传递urlheaders,则必须将null传递为data

axios.post(url, null, headers)

或者你可以试试Axios api

Axios({
    method: 'post',
    url: 'http://localhost:4200/api/viewSubAdmin',
    headers: authHeader()
}).then.....

【讨论】:

  • 谢谢@iamhuynq,你救了我的命,你能解释一下为什么我的代码不工作
  • 不确定,但我认为 axios post 期望将数据作为参数传递,如果您只传递 URL 和标头,标头将被视为数据。所以我认为你可以通过null 来请求axios.post(url, null, headers),它也许可以修复这个错误
  • 很高兴它有帮助!
【解决方案2】:

您的代码有一点错误我已经修改了您的代码。请将您的 axios 调用替换为以下代码并检查

Axios.post('http://localhost:4200/api/viewSubAdmin',{
            headers: authHeader()
          }).then(result => {
              console.log(result)
              this.setState({
               isLoaded: true,
               items: result.data
              })
            }).catch(error => {
                this.setState({
                 isLoaded: true,
                 error
               })
              });

【讨论】:

    猜你喜欢
    • 2013-01-21
    • 2018-02-26
    • 2020-03-09
    • 2016-03-08
    • 1970-01-01
    • 2020-03-25
    • 2020-05-10
    • 2020-12-05
    • 2015-05-26
    相关资源
    最近更新 更多