简体   繁体   中英

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

I'm getting struggle with this code, so I need a third eye on this to find a solution.

I'm developing a ReactJS app with a REST API with Node.JS (Express), and I'm getting this error:

SyntaxError: "JSON.parse: unexpected character at line 1 column 1 of the JSON data"

I'm using Sequelize ORM to work with Models and Database in Node.JS. I'm also using CORS module for Node.JS.

This implementation works fine.

// 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"})
        });
}

On the other hand, this implementation do not work properly and throws the SyntaxError above:

// 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."})
            });
    }

As you can see both implementation have little differences, What am I missing?

PS: When I test the 2nd implementation on Postman, data is retrieving successfully.

try removing headers when using GET method

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

Try to use res.json instead of res.send in the node js function that cause the error.

I found the issue!

I follow the ( @vengleab so ) suggestion:

console log response instead of response => response.json()

I'm realize that response returns an object like this:

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"
}

The URL attribute contain an undefined value, so when I try to console.log the .env variable API_URL that contains the localhost URL used in this line:

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

That in real function is:

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

The result of the console.log was undefined .

As it is explained in Create React App docs, the environment variables must start with the prefix REACT_APP_ .

Finally the line works as:

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

I found that it was because my front end react url pointed to the same url as my backend server.js running mongodb. Also clearing the cookies on the browser seems to have helped as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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