【发布时间】:2016-10-21 19:48:27
【问题描述】:
我正在尝试在 Redux 中进行身份验证的 POST 请求,我将电子邮件和密码作为正文传递,但它在控制台中返回此错误:
Uncaught (in promise) SyntaxError: Unexpected end of input
我四处寻找答案,许多人认为它可能是缺少} 大括号,但我寻找它,但我认为不是那个。
这是我的 fetch 函数。
export function loginUser(creds) {
let config = {
mode: 'no-cors',
method: 'POST',
headers: { 'Content-Type':'application/x-www-form-urlencoded' },
body: `email=${creds.email}&password=${creds.password}`
};
return dispatch => {
dispatch(requestLogin(creds));
return fetch('http://localhost:4000/api/authenticate', config)
.then(response =>
response.json()
.then(user => ({ user, response }))
).then(({ user, response }) => {
if (!response.ok) {
dispatch(loginError(user.message));
return Promise.reject(user);
} else {
localStorage.setItem('id_token', user.token);
dispatch(receiveLogin(user));
}
});
};
}
fetch POST 方法调用 API,我在网络选项卡中看到它,我也看到了响应,但是 fetch 请求在 url 和配置之后停止在 .then(response =>。
已经两天了,仍然找不到解决方案。顺便说一句,这在 Postman(chrome 扩展)中运行良好,所以 API 没有问题。
谢谢
回答编辑:该问题与 CORS 有关,因此对于与我遇到相同问题的任何人。
【问题讨论】:
-
什么是
response.json()? -
@RIYAJKHAN 这是 API 的响应,包含很多关于请求的信息,例如成功与否,成功时的数据等
-
但是你在responce上使用的是json方法。不是吗?
-
@RIYAJKHAN 是的,我是。
-
@RIYAJKHAN 我认为您不了解基于承诺的 API 调用。在这里阅读:davidwalsh.name/fetch 响应由 fetch 提供,它带有一组方法,其中一个是
.json()
标签: javascript api reactjs http-post redux