繁体   English   中英

ReactJS 和 Node.JS [JSON.parse:JSON 数据的第 1 行第 1 列的意外字符]

[英]ReactJS and Node.JS [JSON.parse: unexpected character at line 1 column 1 of the JSON data]

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

我正在使用 Node.JS(Express)开发 ReactJS 应用程序和 REST API 应用程序,我收到此错误:

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 上测试第二个实现时,数据检索成功。

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

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

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

我发现了问题!

我遵循( @vengleab so )建议:

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

我意识到response返回一个 object ,如下所示:

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', {

真正的 function 是:

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

console.log 的结果是undefined

正如Create React App文档中所解释的,环境变量必须以前缀REACT_APP_

最后,该行的工作方式为:

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

我发现这是因为我的前端反应 url 指向与运行 mongodb 的后端 server.js 相同的 url。 清除浏览器上的 cookies 似乎也有帮助。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM