【问题标题】:Get request working on Postman, but not in React.js?获取在 Postman 上工作的请求,但不在 React.js 中?
【发布时间】:2020-05-02 19:11:21
【问题描述】:

我的 API GET 请求在 Postman 中有效,但在 React.JS / 浏览器中无效。我必须在 URL 的开头传入用户名和密码才能访问 API 信息,这在 Postman 中也可以正常工作,但在 React/浏览器中不能正常工作。

我的 GET 请求如下所示:

http://username:password@mywebsite.com:4040/api/stuff/stuff2

它可以在 Postman 中使用,但是当我在 React 中执行 axios GET 请求时,在 console.logs 中看起来请求的用户名:密码部分已被删除,并且我收到一个错误代码,说我未经授权。

这是 React 代码:

    getList = () => {
        axios
            .get('http://username:password@mywebsite.com:4040/api/stuff/stuff2')
            .then(res => {
                console.log(res)
                this.setState({
                    list: res.data
                })
            })
            .catch(err => console.log(err))
    }

你知道如何让 GET 请求在 React 中工作吗?

【问题讨论】:

    标签: javascript axios postman


    【解决方案1】:

    您正在尝试使用 basic access authentication 这在 Postman 中有效,因为 Postman 不执行 AJAX 请求,浏览器根本不允许您在 AJAX 请求 URL 中传递该信息。

    以前回答过here

    您可以将身份验证作为选项传递给您的 axios.get 调用,如下所示:

    axios.get(
      'http://mywebsite.com:4040/api/stuff/stuff2', 
       {
         auth: {
           username: 'username',
           password: 'password'
         }
       }
    )
    

    【讨论】:

      猜你喜欢
      • 2014-12-07
      • 2020-05-26
      • 1970-01-01
      • 2022-01-12
      • 2020-06-20
      • 2018-03-04
      • 1970-01-01
      • 2020-08-02
      • 1970-01-01
      相关资源
      最近更新 更多