【问题标题】:Fetch POST Unexpected end of input ErorrFetch POST Unexpected end of input Error
【发布时间】: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


【解决方案1】:

我在删除时解决了同样的问题

mode: 'no-cors'

来自配置。

【讨论】:

    【解决方案2】:

    无论如何,您都可以将您的 sn-p 代码简化为:

    fetch('http://localhost:4000/api/authenticate', config)
      .then(response => response.json())
      .then(({ user, response }) =>  {
    

    您应该添加 catch 方法来处理错误对象。

    【讨论】:

      猜你喜欢
      • 2021-11-06
      • 1970-01-01
      • 2019-11-21
      • 2017-06-24
      • 2018-02-19
      • 2021-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多