3

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.

2
  • What's the reason for stringifying the data you just parsed as json? this.setState({posts: JSON.stringify(json.posts.rows)}) Commented Sep 10, 2019 at 3:37
  • It just kept there when I copied from another router example. Already fixed in the code example. Modify it do not represent positive results. Commented Sep 10, 2019 at 3:43

4 Answers 4

3

try removing headers when using GET method

headers: {
       'Content-Type': 'application/json'
}
Sign up to request clarification or add additional context in comments.

4 Comments

you can try to console log response instead of response => response.json(), maybe the response might be error from your try catch code, not json data
@YulioAlemanJimenez, or maybe you can try using axios instead of fetch
When replace response.json() by response I get this 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" ​ } Note the URL, why it is concatenating React URL + undefined + Node.JS route path??
Neither do i, it is from fetch lib
2

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

Comments

0

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

1 Comment

Try to add consoles inside the node's successful query function.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.