Reputation: 869
I'm using a MongoDB, Node, Express and React.js. I'm not able to receive data from my node.js server to my react.js client. This is the error I have: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
. I know its a very common error but none of the solutions I found seems relevant for my context.
Here's the package.json line where my proxy is initialized:
"proxy": "http://localhost:5000",
Here's my express routing:
app.get('/main-data', (req, res) => {
MongoClient.connect(connectionURL, {
useNewUrlParser: true,
}, (error, client) => {
if(error){
return console.log("Unable to connect to the db.");
}
const db = client.db(databaseName);
db.collection("metadata_from_bot")
.find()
.toArray((error, data) => {
console.log(data);
res.json(data);
});
})
res.json({hello: "world"})
})
Here's my react fetch:
componentDidMount() {
fetch('/main-data')
.then(res => res.json())
.then(data => this.setState({ data }));
}
When I go to http://localhost:5000/main-data
, I receive the following output:
When I inspect the network tab, here's what I have: Status Code: 304 Not Modified
.
However, when I click on the link (http://localhost:3000/main-data) in the network-tab, I get the error.
The data should be set to the state but now I'm not able to receive it in JSON format.
Upvotes: 0
Views: 1202
Reputation: 1409
I'm not sure but shouldn't you use host in fetch
componentDidMount() {
fetch('http://localhost:5000/main-data')
.then(res => res.json())
.then(data => this.setState({ data }));
}
Upvotes: 1