【问题标题】:ReactJS and Node.JS [JSON.parse: unexpected character at line 1 column 1 of the JSON data]ReactJS 和 Node.JS [JSON.parse:JSON 数据的第 1 行第 1 列出现意外字符]
【发布时间】:2020-01-11 18:58:40
【问题描述】:

我对这段代码感到困惑,所以我需要第三眼来寻找解决方案。

我正在使用带有 Node.JS (Express) 的 REST API 开发一个 ReactJS 应用程序,但我收到了这个错误:

SyntaxError:“JSON.parse:JSON 数据的第 1 行第 1 列出现意外字符”

我正在使用Sequelize ORM 在 Node.JS 中处理模型和数据库。 我也在为 Node.JS 使用 CORS 模块。

这个实现工作正常。

// Node.js Route for login
const router = require('express').Router();
const User = require('user');
router.post("/login", async (req, res) => {
    try {
        await User.findOne({
            where: {
                email: req.body.email,
                password: req.body.password,
            }
        }).then((user) => {
            if (!user) {
                return res.send({message: "Login error!"});
            } else {
                const userData = {id: user.id, email: user.email};
                res.send({"user": userData});
            }
        }).catch((err) => {
            return res.send(err);
        });
    } catch (err) {
        return res.send(err);
    }
});
// ReactJS for login
loginFunction(e, data) {
    e.preventDefault();
    fetch('http://localhost:4500/login', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
        .then(response => response.json())
        .then(json => {
            this.setState({'user': json['user']});
        })
        .catch((err) => {
            console.log(err);
            this.setState({errors: "Login error"})
        });
}

另一方面,这个实现不能正常工作并抛出上面的SyntaxError

// Node.JS for Posts
const router = require('express').Router();
const Post = require('post');
router.get("/posts", async (req, res) => {
    try {
        await Post.findAndCountAll()
            .then((posts) => {
                res.send({"posts": posts});
            }).catch((err) => {
                return res.send(err);
            });
    } catch (err) {
        return res.send(err);
    }
});
// ReactJS for Posts
postsFunction() {
        fetch('http://localhost:4500/posts', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            }
        })
            .then(response => response.json())
            .then(json => {
                this.setState({'posts': json.posts.rows});
            })
            .catch((err) => {
                console.log(err);
                this.setState({errors: "Posts error."})
            });
    }

如您所见,这两种实现方式差别不大,我缺少什么?

PS:当我在 Postman 上测试第二个实现时,数据检索成功。

【问题讨论】:

  • 将刚刚解析为json的数据进行字符串化的原因是什么? this.setState({posts: JSON.stringify(json.posts.rows)})
  • 当我从另一个路由器示例复制时,它只是保留在那里。已在代码示例中修复。修改它并不代表积极的结果。

标签: javascript node.js json reactjs sequelize.js


【解决方案1】:

在使用 GET 方法时尝试删除标题

headers: {
       'Content-Type': 'application/json'
}

【讨论】:

  • 您可以尝试控制台日志response 而不是response => response.json(),可能响应可能是您的try catch 代码错误,而不是json 数据
  • @YulioAlemanJimenez,或者您可以尝试使用axios 而不是fetch
  • 当将response.json() 替换为response 我得到这个对象:Response: { ​ body: ReadableStream ​​ locked: false ​​ <prototype>: object { … } ​ bodyUsed: false ​ headers: Headers { } ​ ok: true ​ redirected: false ​ status: 200 ​ statusText: "OK" ​ type: "basic" ​ url: "http://localhost:3000/admin/undefined/posts" ​ } 注意URL,为什么它是连接React URL + undefined + Node.JS 路由路径??
  • 我也没有,来自fetch lib
【解决方案2】:

尝试在导致错误的节点js函数中使用res.json而不是res.send。

【讨论】:

  • 尝试在节点成功查询函数内添加控制台。
【解决方案3】:

我发现了问题!

我遵循 (@vengleab so) 的建议:

控制台日志response 而不是response => response.json()

我意识到response 返回一个像这样的对象:

Response: {
    body: ReadableStream
    locked: false
    <prototype>: object { … }
    bodyUsed: false
    headers: Headers { }
    ok: true
    redirected: false
    status: 200
    statusText: "OK"
    type: "basic"
    url: "http://localhost:3000/admin/undefined/posts"
}

URL 属性包含一个undefined 值,因此当我尝试控制台记录.env 变量API_URL 时,该变量包含此行中使用的本地主机URL:

fetch('http://localhost:4500/posts', {

真正的功能是:

fetch(process.env.API_URL + '/posts', {

console.log 的结果是undefined

正如Create React App 文档中所述,环境变量必须以前缀REACT_APP_ 开头。

最后一行是:

fetch(process.env.REACT_APP_API_URL + '/posts', {

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-14
    • 2016-01-30
    • 1970-01-01
    • 1970-01-01
    • 2020-10-13
    • 2019-05-11
    • 2017-05-18
    • 2020-04-17
    相关资源
    最近更新 更多