Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 685
Yulio Aleman Jimenez Avatar asked Dec 06 '25 05:12

Yulio Aleman Jimenez


2 Answers

try removing headers when using GET method

headers: {
       'Content-Type': 'application/json'
}
like image 101
Vengleab SO Avatar answered Dec 08 '25 19:12

Vengleab SO


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', {
like image 34
Yulio Aleman Jimenez Avatar answered Dec 08 '25 20:12

Yulio Aleman Jimenez