【问题标题】:React JS - 404 - (Not Found) error when attempting to consume json API尝试使用 json API 时出现 React JS - 404 - (Not Found) 错误
【发布时间】:2018-10-27 01:20:39
【问题描述】:

我正在关注使用 JWT 进行 React JS 身份验证的教程,并创建了一个使用 json api 的登录表单,该表单在输入正确的用户名和密码后生成一个令牌。当我单击提交按钮时,我收到 404 错误 - 未找到(通过 chrome 控制台/网络选项卡)。但是,当我通过邮递员测试 API 时(在正文中输入用户名和密码(json),会返回一个令牌)

登录页面调用另一个文件中的函数,用于验证用户并获取令牌。 我想知道我的 fetch 语句是否设置正确,这就是我所拥有的

登录方式

login(username, password) {
        // Get a token from api server using the fetch api
        return this.fetch(`${this.domain}/login`, {
            method: 'POST',
            body: JSON.stringify({
                username,
                password
            })
        }).then(res => {
            this.setToken(res.token) // Setting the token in localStorage
            return Promise.resolve(res);
        })
    } 

...这是我的获取方法

fetch(url, options) {
        // performs api calls sending the required authentication headers
        const headers = {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        }

        // Setting Authorization header
        // Authorization: Bearer xxxxxxx.xxxxxxxx.xxxxxx
        if (this.loggedIn()) {
            headers['Authorization'] = 'Bearer ' + this.getToken()
        }

        return fetch(url, {
            headers,
            ...options
        })
            .then(this._checkStatus)
            .then(response => response.json())
    }

下面,如果有帮助,我会发布完整代码的网址:

Login https://codepen.io/lkennedy009/pen/GdYOYe?editors=0010#0
AuthService https://codepen.io/lkennedy009/pen/xjyPMY
withAuth https://codepen.io/lkennedy009/pen/bMmYyd?editors=0010#0

...关于我做错了什么和/或我是否遗漏了什么,我能得到一些帮助吗?

【问题讨论】:

    标签: json reactjs api fetch


    【解决方案1】:

    看起来您的 fetch 设置没问题,而且您的 API 使用邮递员工作,但通过您发布的代码调用时却不行,这让我认为 ${this.domain}/login/ 没有产生您期望的输出.

    我注意到您在创建 AuthService 实例时没有提供域,这将导致域回退到 http://theApiUrl:11111/api/auth。我会将一些 console.log 语句放入 fetch 方法中,然后查看 url 提供的值。

    【讨论】:

    • 感谢史蒂夫,问题出在 ${this.domain}/login/ 中,再次感谢您让我走上正确的道路。
    猜你喜欢
    • 2012-09-27
    • 1970-01-01
    • 2017-10-19
    • 1970-01-01
    • 2021-01-12
    • 1970-01-01
    • 1970-01-01
    • 2021-06-16
    • 2019-08-02
    相关资源
    最近更新 更多