ali
ali

Reputation: 1

I am getting error when I fetch Data from my backend?

I am running my backend on "http://localhost:3001/" using expressjs

app.listen(3001, function() {
    console.log('Server is running');
});

my frontend on "http://localhost:3000/" using react but when i fetch data I am getting an error

package.json
    "proxy": "http://localhost:3001",

componentDidMount() {
        const fetchData = async () => {
            fetch('/data')
                .then(res => res.json())
                .then(d => console.log(d));
        };
        fetchData();
    }

here is the error

Upvotes: 0

Views: 363

Answers (2)

Benz Stevox
Benz Stevox

Reputation: 162

Does the "/data" route exist?

If it doesn't, you're trying to extract JSON from a html file and hence the error. Remove .then(res => res.json()) until you define the route on your server.

Upvotes: 0

Rahul Pillai
Rahul Pillai

Reputation: 187

Your proxy in the package.json file on the client should be set to whatever server you are trying to connect to on the backend:

package.json
    "proxy": "http://localhost:3001",

Upvotes: 2

Related Questions