'Uncaught (in promise) SyntaxError: Unexpected token T in JSON at position 0
When I try send an array of data to the frontend, it works fine, but when I try to send a sample text to the frontend from the server, getting the error Unexpected token T in JSON at position 0. I am getting this error on console.log(data).
fetch("/something", {
method: "POST",
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data)
}).then(function (response) {
// The API call was successful!
console.log(response);
return response.json();
}).then(function (data) {
// This is the JSON from our response
console.log(data);
});
router.post('/something', () => {
console.log(req.body);
res.send('This is sample');
});
Solution 1:[1]
This is because res.send() automatically sets the Content-Type response header as well based on the argument passed to the send() method. In your case, send() is not detecting a json object as an argument. So, the content type is not json in the response header.
You could use res.json() method to send the string as json.
router.post('/something', () => {
console.log(req.body);
res.json('This is sample');
});
Or, pass a javascript object to res.send() and it would automatically convert it into json.
router.post('/something', () => {
console.log(req.body);
res.send({data: 'This is sample'});
});
Note: res.json() uses res.send() under the hood. Read this article to understand the difference between the two methods.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Amit |
