尝试获取 api 时出现 Axios 错误 401(未经授权)错误

时间:2021-03-04 04:42:35

标签: javascript reactjs api axios postman

<块引用>
  • 错误:请求失败,状态码为 401
  • 在 createError (createError.js:16) - 在结算 (settle.js:17)
  • 在 XMLHttpRequest.handleLoad (xhr.js:62)
import React, { Component } from 'react'
import axios from 'axios';
class QuestionAPI extends Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [],
      MYTOKEN: "cqondiodwoidndndjjajajejh.ndoqndnodnqodoqdiapoe89wnwjwmalmqql2mkKKMkmwk"
    };
  }
  componentDidMount = (MYTOKEN) => {
    axios.get(`http://192.168.0.10:9000/getquestions`,{
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        "token": 'Bearer' + MYTOKEN
      },
    })
      .then(res => {
        console.log("res" + res)
      })
      .catch(e => console.log(e))
  }
  render() {
    return (
      <div>
      </div>
    );
  };
}
export default QuestionAPI;

1 个答案:

答案 0 :(得分:2)

您的代码存在一些问题。

  • componentDidMount 方法不接收任何参数。因此,您必须从 localStorage 获取令牌(假设您将令牌存储在其中)。您应该从组件状态中删除硬编码的令牌。

  • 令牌应在 Authorization 标头中发送(您的代码在 token 中发送它,这就是 API 发送 401 Unauthorized 响应的原因)。并且 Bearer 旁边应该有一个空格。

Authorization: `Bearer ${token}`
componentDidMount = () => {
  const token = localStorage.getItem('token') // Replace token with the right key
  if (!token) {
    // handle no token case
    return
  }

  axios.get(`${process.env.API_BASE_URL}/getquestions`, {
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json',
      Authorization: `Bearer ${token}`,
    },
  })
}