This question arouse while working with these technologies- React.js | Node.js | Express.js | MongoDB
I developed an API endpoint api/events/allevents as following-
router.get('/allevents', async (req, res) => {
let success = false;
try{
const allevents = await Event.find({});
success = true;
res.json({success, allevents});
}
catch(err){
res.status(400).json({ success: success, error: "no events found" });
}
})
And I tested it in Thunder Client in VS Code and everything is perfect with the following response-
{
"success": true,
"allevents": [
{
"_id": "62d021d273b4565d056574ac",
"title": "The Summer Night",
"description": "The Summer Night is a musical night in which singers and bands will perform live.",
"address": "New Delhi Auditorium",
"city": "New Delhi",
"state": "New Delhi",
"country": "India",
"days": 1,
"date": "30/7/2022"
}
]
}
Then after it I was trying to call it by the following function in a React.js component as following-
async function fetchAllEvents() {
const response = await fetch('/api/events/allevents', {
method: 'get',
}
);
console.log(response);
let json = await response.json();
console.log(json);
}
fetchAllEvents();
And in Edge browser's console, this is the response-
Why I am not getting the expected response same as above in Thunder Client's case ? I know I am very close to get the correct response, but I am not getting what is that little error . Can you help me with that ? Also it would be a great help if someone explains in detail how the api endpoint definition and api call are communicating to each other.
Kindly ignore the mistakes as it is from a beginner's side :)
Unexpected token < means response is HTML instead of JSON, Reason could be other thing than code shared over here. You can easily identify it by looking console of browser devtool console / network tab. By looking at code here, change you should make are,
send response as jsonp ( much convenient on transport then json )
router.get('/allevents', async (req, res) => {
let success = false;
try{
const allevents = await Event.find({});
success = true;
res.jsonp({success, allevents});
}
catch(err){
res.status(400).json({ success: success, error: "no events found" });
}
})
async function fetchAllEvents() {
try {
const response = await fetch('/api/events/allevents', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}
);
console.log(response);
let json = await response.json();
console.log(json);
}
catch(error) {
console.error(error)
}
}
fetchAllEvents();