首页 > 解决方案 > Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 (React/Redux App)

问题描述

我正在尝试使用 JWT 注册/登录用户。为此,我创建了一个可用的 API。

现在,我想在我的 React/Redux 应用程序中使用该身份验证 API。

当用户注册时dispatch,我的注册组件中的一个操作 -

const signUpHandler = (e) => {
    e.preventDefault();

    dispatch(signup(name, email, password));
  };

现在,在我的userSlice我有以下减速器 -

signup: (state, action) => {
      fetch("http://localhost:5000/user/signup", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(action.payload),
      })
        .then((res) => {
          return res.json();
        })
        .then((data) => {
          console.log(data);
        });
    },

在我点击注册后,即;该fetch过程开始后,我收到此错误-

Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

经过一点点挖掘,我发现当返回类型fetch不是JSON时会发生此错误。但我的 API 运行良好。

知道可能是什么问题吗?

提前致谢。

标签: javascriptnode.jsreactjsexpressredux

解决方案


我刚刚发现了这个错误,这很愚蠢。这可能会阻止某人犯同样的错误。

发送注册/登录操作时,

代替dispatch(signup(name, email, password));

做 - dispatch(signup({name, email, password}));

主要错误是action.payload不是预期的(即对象)。因此发送到服务器的数据不正确。


推荐阅读