【问题标题】:401 Mysterious unauthorized401神秘未授权
【发布时间】:2020-09-29 16:41:42
【问题描述】:

各位程序员们好,

我遇到了以下问题。我用 axios 做了一个 post 请求,如下所示:

componentDidMount() {
    const config = {
      headers: { Authorization: `Bearer ${Auth.getToken()}` },
    };
    const urlCategories = "http://localhost:8090/category";
    axios.get(urlCategories, config).then((res) => {
      const categories = res.data;
      this.setState({ categories });
      console.log(this.state.categories);
    });
    const urlTricks = "http://localhost:8090/trick/" + Auth.parseJwt().sub;
    axios.get(urlTricks, config).then((res) => {
      const tricks = res.data;
      this.setState({ tricks });
      console.log(this.state.tricks);
    });
  }

这行得通! :D

然后我想做同样的事,但后来,所以我几乎复制了这个但是...... 我得到了 401,而我看不出两者之间有任何真正的区别。我什至问过我的老师,他也不知道答案。

handleChecked = () => {
    if (this.state.learned) {
      this.setState(
        {
          learned: false,
        },
        () => {
          console.log("Should be false and is: " + this.state.learned);
          const config = {
            headers: { Authorization: `Bearer ${Auth.getToken()}` },
          };
          axios
            .post(
              "http://localhost:8090/user/" +
                Auth.parseJwt().sub +
                "/" +
                this.props.id +
                "/" +
                this.state.learned,
              config
            )
            .then(() => {
              console.log(this.props.name + " set to: " + this.state.learned);
            });
        }
      );
    } else { }

奇怪的是;它在 Postman 中工作,所以我的结论是前端一定有问题。后端应该没问题。如果你很好奇: Auth.parseJwt().sub 获取用户名(我知道这是一个奇怪的用户名名称)。另一个奇怪的事情是,当我复制 Chrome Inspect 概述中的 URL 并在 Postman 中使用它时,它可以工作......

有人知道或看到这段代码有什么问题吗?

【问题讨论】:

    标签: post request axios


    【解决方案1】:

    我的名字是 Appeltaart,如果它在邮递员中工作,后端应该没问题,就像你说的那样。你可以从头开始你的应用程序或试试这个:D

    axios.post(`http://localhost:8090/user/${Auth.parseJwt().sub}/${this.props.id}/${this.state.learned}`, {
            headers: {
                Authorization: `Bearer ${Auth.getToken()}`,
                "Content-Type": "application/json"
            }
        }).then(() => {
            console.log(this.props.name + " set to: " + this.state.learned);
        });
    
    

    友好的问候, 你的小苹果

    【讨论】:

    • 感谢您的回答 Appeltaart。不幸的是,这并没有解决它。我仍然停留在这部分。我的应用程序已完成 :) 但只有这部分还没有工作......
    • 那么你会怎么做呢? :(
    • 我没有修复它,但是几天前我的学校评估已经完成了,包括这个错误:') 但是很好,我的老师看到了代码并且有一种我理解的感觉它。但感谢您输入 Appeltaart。我很感激! :)
    • 啊很高兴听到你通过了!没问题,兄弟,你是最棒的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-06
    • 2018-05-19
    • 2020-06-11
    • 2017-02-22
    • 2018-10-08
    • 2018-01-05
    • 2019-04-30
    相关资源
    最近更新 更多