0

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

  • The `unexpected token <` error, in my experiences, often indicates that an API call resulted in something other than JSON (usually HTML) in the response. That's probably happening because the `.then` is being called which is trying to do `res.json()`. Fetch does not throw an error when the response status code is 400. You should figure out why it's resulting in a 400 Bad Request from the API, as well as check for a valid response status code in `.then`. – Matt U Sep 11 '21 at 14:42
  • try to remove than() . you are using tww then in function remove data then(). – Tushar Sep 11 '21 at 14:43
  • @Matt U uh i'm receiving a text/htmt even though im try to send a json response –  Sep 11 '21 at 15:09
  • Does this answer your question? [Unexpected token < in JSON at position 0](https://stackoverflow.com/questions/38821751/unexpected-token-in-json-at-position-0) – Jared Smith Sep 11 '21 at 17:08
  • @Jared Smith i don't know how i would apply the accepted answer I'm running the server on localhost –  Sep 11 '21 at 17:41
  • @pymdarc this is a super common error when parsing JSON in Javascript (especially when dealing with server responses). Just as is said in the top answers on that linked dupe, you're getting HTML back from your server instead of JSON. The usual culprit is the 404 page because the front end API call doesn't match the route defined on the server. In your particular case it looks like your fetch for `/elpers/search` might be missing an 'h'. – Jared Smith Sep 11 '21 at 19:58

2 Answers2

0

You need to use res.json() instead of res.send() and JSON.stringify(e.value) to JSON.stringify({result: e.value})

0

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!

Mike0608
  • 29
  • 5
  • 1
    i don't think the fetch request is reaching the route because it isn't logging the req.body the errors are the same –  Sep 11 '21 at 18:28
  • If you're not reaching the route, you won't receive anything, maybe that's where the problem is. If you're using ExpressJS, try a simple route from the backend like this. `app.post(/route, (req, res) => {console.log(req.body}; res.json({message: "data received!"}));` – Mike0608 Sep 11 '21 at 18:33
  • 1
    Nope its still not reaching the route does fetch works differently with localhost? –  Sep 11 '21 at 18:48
  • No, try to put the entire localhost in the request url. example: "http://localhost:8080/elpers/search". Make sure the link is correct. – Mike0608 Sep 11 '21 at 18:50
  • nope same thing also even before using the whole route the post route did try sending it to http://localhost:3000/elpers/search –  Sep 11 '21 at 19:07
  • If nothing shows on the express console, check your backend code or post it. – Mike0608 Sep 11 '21 at 19:11
  • by post it if you mean form submit then it works and its logs on the console so would that mean the backend is working? –  Sep 11 '21 at 19:18
  • Does the log contains the data the server is supposed to send? then yes. by post, i meant "show us the code" lol – Mike0608 Sep 11 '21 at 19:22
  • Oh my bad ```app.post('/route', (req, res) => { console.log(req.body); res.json({message: "data received!"}) });``` Route and fetch : ```const searchResults = function(e){ fetch('http://localhost:3000/route' ,{ method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(e.value) }).then(res => { console.log(res) console.log(res.status) res.json() }).then(data => { console.log(data) }).catch(err => { console.error(err) }) }``` sorry for the bad format –  Sep 11 '21 at 19:39
  • Make one promise on the client side and console.log(res) only, what comes from that? – Mike0608 Sep 11 '21 at 20:01
  • promise seems to work on its own and if you meant fetch promise i tried a get request on /elpers and it works aswell –  Sep 11 '21 at 20:21
  • GET and POST are two different things, when you send the post request above, what do you get on console.log(res)? – Mike0608 Sep 11 '21 at 20:29
  • I get the response object on the console with status 400 is there something more specific in it you need to know?? –  Sep 12 '21 at 01:55
  • ```JSON.stringify({result: e.value}) ``` this worked for me i don't why it didn't when i sent an object like so ```{'result: 'value'}``` –  Sep 12 '21 at 06:59