javascript - Axios Error 401 (Unauthorized) Error when trying to fetch API - Stack Overflow

Error: Request failed with status code 401at createError (createError.js:16)-at settle (settle.js:17)

  • Error: Request failed with status code 401
  • at createError (createError.js:16) -at settle (settle.js:17)
  • at 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"
    };
  }
  ponentDidMount = (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;
  • Error: Request failed with status code 401
  • at createError (createError.js:16) -at settle (settle.js:17)
  • at 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"
    };
  }
  ponentDidMount = (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;
Share Improve this question edited Jan 27 at 17:28 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Mar 4, 2021 at 4:42 Patel NeelPatel Neel 901 silver badge8 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 3

There are a few issues with your code.

  • The ponentDidMount method doesn't receive any arguments. So, you have to get the token from localStorage (assuming you're storing the token in it). And you should remove the hardcoded token from the ponent state.

  • The token should be sent in the Authorization header (your code sends it in token and that's why the API sends a 401 Unauthorized response). And there should be a space next to Bearer.

Authorization: `Bearer ${token}`
  • You shouldn't hardcode the API URL. Use environment variables. If you're using Create React App, you can add environment variables prefixed with REACT_APP_ to .env or you can use dotenv-webpack if you have a custom Webpack setup.
ponentDidMount = () => {
  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}`,
    },
  })
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745301650a4621469.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信