【发布时间】: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
...关于我做错了什么和/或我是否遗漏了什么,我能得到一些帮助吗?
【问题讨论】: