简体   繁体   English

为什么我在 JSON 中的位置 0 处收到 Unexpected token < 的错误

[英]Why am I getting an error of Unexpected token < in JSON at position 0

I am creating a MERN app, I am new to this.我正在创建一个 MERN 应用程序,我是新手。 I tried following some tutorials on the net but I have encountered some error.我尝试在网上学习一些教程,但遇到了一些错误。

I am submitting the post request like this.我正在提交这样的帖子请求。 As you can see I am not specifying the content type because I know that if you are using the 'multipart/form-data it will automatically append it to the headers.正如您所看到的,我没有指定内容类型,因为我知道如果您使用的是“multipart/form-data”,它会自动将其附加到标题中。 I am using a react hook here which is why I am not directly using the fetch method.我在这里使用了一个 react 钩子,这就是为什么我没有直接使用 fetch 方法。

const formData = new FormData();
formData.append("email", formState.inputs.email.value);
formData.append("name", formState.inputs.name.value);
formData.append("password", formState.inputs.password.value);
formData.append("image", formState.inputs.image.value);
const responseData = await sendRequest(
    `${process.env.REACT_APP_BACKEND_BASE_URL}/api/users/signup`,
    "POST",
    formData
    );

meanwhile my signup route is like this, UNDER user-routes.js同时我的注册路线是这样的,在user-routes.js 下

router.post(
  "/signup",
  fileUpload.single("image"),
  [
    check("name").not().isEmpty(),
    check("email")
      .normalizeEmail() // Test@test.com => test@test.com
      .isEmail(),
    check("password").isLength({ min: 6 }),
  ],
  usersController.signup
);

as you can also see, I am catching it in the route by using the fileUpload.single("image")如您所见,我通过使用fileUpload.single("image")在路由中捕获它

if you need to see my hook that I am using here it is, but I am pretty sure that the hook works fine.如果你需要看看我在这里使用的钩子,它是,但我很确定钩子工作正常。 and it has no issues whatsoever, so here it is: this is a react hook它没有任何问题,所以这里是:这是一个反应钩子

export const useHttpClient = () => {
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState();

  const activeHttpRequests = useRef([]);

  const sendRequest = useCallback(
    async (url, method = "GET", body = null, headers = {}) => {
      setIsLoading(true);
      const httpAbortCtrl = new AbortController();
      activeHttpRequests.current.push(httpAbortCtrl);

      try {
        const response = await fetch(url, {
          method,
          body,
          headers,
          signal: httpAbortCtrl.signal,
        });

        const responseData = await response.json();

        // console.log("Response: ", response);
        // console.log("Data: ", responseData);

        activeHttpRequests.current = activeHttpRequests.current.filter(
          (reqCtrl) => reqCtrl !== httpAbortCtrl
        );

        if (!response.ok) {
          throw new Error(responseData.message);
        }

        setIsLoading(false);
        return responseData;
      } catch (err) {
        setError(err.message);
        setIsLoading(false);
        throw err;
      }
    },
    []
  );

  const clearError = () => {
    setError(null);
  };

  useEffect(() => {
    return () => {
      // eslint-disable-next-line react-hooks/exhaustive-deps
      activeHttpRequests.current.forEach((abortCtrl) => abortCtrl.abort());
    };
  }, []);

  return { isLoading, error, sendRequest, clearError };
};

I will include the signup here from my users.controller :我将从我的users.controller包括在这里注册:

const signup = async (req, res, next) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return next(
      new HttpError("Invalid inputs passed, please check your data.", 422)
    );
  }

  const { name, email, password } = req.body;

  let existingUser;
  try {
    existingUser = await User.findOne({ email: email });
  } catch (err) {
    const error = new HttpError(
      "Signing up failed, please try again later.",
      500
    );
    return next(error);
  }

  if (existingUser) {
    const error = new HttpError(
      "User exists already, please login instead.",
      422
    );
    return next(error);
  }

  let hashedPassword;
  try {
    hashedPassword = await bcrypt.hash(password, 12);
  } catch (err) {
    const error = new HttpError(
      "Could not create user, please try again.",
      500
    );
    return next(error);
  }

  //res.json({ message: "AFTER HASHING" });

  const createdUser = new User({
    name,
    email,
    image: req.file.path,
    password: hashedPassword,
    places: [],
  });

  try {
    await createdUser.save();
  } catch (err) {
    const error = new HttpError(
      "Signing up failed, please try again later.",
      500
    );
    return next(error);
  }

  let token;
  try {
    token = jwt.sign(
      { userId: createdUser.id, email: createdUser.email },
      process.env.JWT_KEY,
      { expiresIn: "1h" }
    );
  } catch (err) {
    const error = new HttpError(
      "Signing up failed, please try again later.",
      500
    );
    return next(error);
  }

  res
    .status(201)
    .json({ userId: createdUser.id, email: createdUser.email, token: token });
};

You may want to use JSON.Parse() around your responseData你可能想在你的 responseData 周围使用JSON.Parse()

When ever I run into this bug it is because I either,每当我遇到这个错误时,都是因为我,

  • parsed an already parsed object解析一个已经解析的对象
  • Stingified a string刺痛了一个字符串
  • Used a string as an object使用字符串作为对象

This link goes into more depth about the bug and common ways of dissecting the issue.链接更深入地了解错误和剖析问题的常用方法。

Try console.log() in your hook before you send the data and also log what the responseData looks like after it retrieves the data在发送数据之前在钩子中尝试 console.log() 并在它检索数据后记录 responseData 的样子

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我正在使用Ionic并收到错误消息:SyntaxError:JSON中的意外标记&lt;在JSON.parse位置0处( <anonymous> ) - I am using ionic and getting an error: SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse (<anonymous>) 为什么我会收到意外令牌\\ - Why am I am getting Unexpected token \ 为什么我在 JSON 文件中收到错误消息“SyntaxError: unexpected token: ':'”? - Why am I getting a error saying “SyntaxError: unexpected token: ':'” in a JSON file? 使用JSON.parse时,出现“ SyntaxError:JSON中位置1的意外令牌” - I am getting “SyntaxError: Unexpected token ' in JSON at position 1” when using JSON.parse 我在 JSON.parse 的位置 0 处不断收到 JSON 中的错误意外令牌 b? - I keep getting the error unexpected token b in JSON at position 0 at JSON.parse? 错误:位置 0 处的 JSON 中出现意外标记 &lt; - Error: Unexpected token < in JSON at position 0 在 position 0 的 json 中发送表单时出现错误 - Getting error when sending form -unexpected token s in json at position 0 为什么在脚本的第一行出现JS错误语法错误:无效或意外的令牌? - Why am I getting the JS error in line one of my script Syntax error: invalid or unexpected token? JSON中位于位置0的意外令牌I - Unexpected token I in JSON at position 0 尝试在简单对象上执行JSON.parse时出现“意外令牌”错误 - I am getting an “Unexpected token” error when trying to do JSON.parse on a simple object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM