Using fetch I'm getting a bad request as well as unexpected token < in JSON both point to search.js which is where I'm making the fetch request I have tried sending via an API client and it is working I'm trying to send the fetch request via input onkeyup. Also noticed my error is uncaught
Fetch req:
const searchResults = function(e){
fetch('/elpers/search' ,
{
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(e.value)
}).then(res => {
res.json()
}).then(data => {
console.log(data)
}).catch(err => {
console.error(err)
})
}
POST route
const postSearch = (req, res) => {
console.log(req.body)
res.send({'result': 'value'});
}
edit: this worked for me JSON.stringify({result: e.value})
Error:
search.js:2 POST http://localhost:3000/elpers/search 400 (Bad Request) VM118:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
You need to use res.json() instead of res.send() and JSON.stringify(e.value) to JSON.stringify({result: e.value})
use this ans let me know:
const postSearch = (req, res) => {
console.log(req.body) // post if data is received here...
res.json({
message: "data received!",
data: search, // search should be the data that user fetched
})
};
On the client side, just console.log the data received and see if it is JSON or not :)))
Happy coding!