简体   繁体   中英

passing header in axios error: 400 bad request

I am trying authorization to my react app using axios and that request works with postman but when I start react it gives me 400 bad request error

    let user = JSON.parse(localStorage.getItem("user"));
    let userName = user.userName;
    let accessToken = user.accessToken;
    console.log(accessToken);
    let config = {
    headers: {
      'Authorization': 'Bearer ' + accessToken
    }
  }
    console.log(config);
    axios.post("http://localhost:8080/getUserType",config).then((response) => {
      var res=response.data;
      this.setState({loginValue:res.userType});
      console.log(res.userType);
    }).catch((err) => {
      console.log(err);
    })
  }

console return this

Dashboard.js:32 Error: Request failed with status code 400
    at createError (createError.js:16)
    at settle (settle.js:17)
    at XMLHttpRequest.handleLoad (xhr.js:61)

Maybe try to directly use the headers instead of encapsulating them in a config variable.

    let user = JSON.parse(localStorage.getItem("user"));
    let userName = user.userName;
    let accessToken = user.accessToken;
    console.log(accessToken);
    let headers: {
      'Authorization': 'Bearer ' + accessToken
    };

    console.log(config);
    axios.post("http://localhost:8080/getUserType", { headers }).then((response) => {
      var res=response.data;
      this.setState({loginValue:res.userType});
      console.log(res.userType);
    }).catch((err) => {
      console.log(err);
    })
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM