首页 > 解决方案 > 我不知道如何解决这个错误:SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

问题描述

我使用 nodeJS 并表达。我不知道如何解决这个错误,请帮助:) 在服务器中:

 app.get("/home", (req, res) => {
        userInfos = bll.retrieveDataUser(); // [userEmail, userPassword, userName, userId]
        res.send({
            userEmail: userInfos[0],
            userPassword: userInfos[1],
            username: userInfos[2],
            uId: userInfos[3]
        });

在客户端:

fetch(`/home`).then((res) => {
        res.json().then((data) => {
            if (data.error) {
                throw error
            } else {
                console.log(data);
            }
        })
    })

谢谢您的帮助 :)

标签: node.js

解决方案


如果你想返回 json 那么你应该使用 express 的res.json方法。

app.get("/home", (req, res) => {
    userInfos = bll.retrieveDataUser(); // [userEmail, userPassword, userName, userId]
    res.json({
        userEmail: userInfos[0],
        userPassword: userInfos[1],
        username: userInfos[2],
        uId: userInfos[3]
    });
)};

并且您的获取请求语法也无效。

    fetch(`/home`)
    .then(res => res.json())
    .then((data) => {
        if (data.error) {
            throw error
        } else {
            console.log(data);
        }
    })

推荐阅读