Home > Software engineering >  node.js express server returns unexpected response to the GET request
node.js express server returns unexpected response to the GET request

Time:09-11

I'm working on the weather app journal, and I am stumbling on some kind of a weird bug I tried searching google, but I couldn't find anything helpful

so here's the problem ![image|603x386](upload://hDuEHsiCfiW3ARNhdyr5nds0yPz.png)

Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON

It appears that fetch returns a response, however when I try using the .json method on fetch it gives an error, and it somehow goes to the first line of the html file. It also appears that the response is empty, it doesn't have the data I wish to send from the server.

this is my GET route for the client side (app.js) file ![image|690x249](upload://kMhs81kWjR7cnnvEDOHo5Q7NMD.png)

this is my code for the GET route on the server side (server.js) file ![image|518x214](upload://dYfLywO6I1ZE6gnTrMayzAltTaZ.png)

note: the console.log("Data Sent") is never printed on the terminal ![image|393x63](upload://nmuIopdbAE1xLe3dVjde2s5nRp1.png)

Edit: I figured out the response I'm getting from the GET request is the html file enter image description here

How can I resolve this problem?

CodePudding user response:

Try to remove

res.send('Data sent!')

CodePudding user response:

The issue you're having is because of using res.send(), you need to use res.json() instead. The second will always return data as application/json, not as HTML which is actually causing that error. That's why it complains about the token <.

On more thing, try to use a single statement to return your response. So, removing res.send('Data Sent!');, convert to console.log() instead or return as part of projectData.

CodePudding user response:

This worked for me

It seems that using the old path "/" resulted in a conflict, as it's the same path used to request the html. Using a new path for the get request solved the problem.

enter image description here

CodePudding user response:

Try to remove

res.send('Data sent!')

If you wanna try send:

res.json(projectData)
  • Related