Issue
Getting the following error:
index.js:1 Unexpected token < in JSON at position 0
It works fine in Postman but it returns the JSON:
<pre>{
"name": "abc123",
"location": "USA",
"notes": "qwerty"
}</pre>
On the client, I am calling this code:
try {
const response = await fetch("http://localhost:5000/search", {
headers: { 'Content-Type': 'application/json'}
});
const jsonData = await response.json();
console.log(jsonData);
} catch (err) {
console.error(err.message);
}
On the server side (express), I have the following code:
app.get('/search', function(req, res) {
let url = `https://myendpoint.com/abcd/search?c=abc123`;
axios({
method:'get',
url
})
.then(function (response) {
res.send(response.data);
})
.catch(function (error) {
console.log(error);
});
});
I would’ve thought by adding headers: { 'Content-Type': 'application/json'}
on the client-side would’ve solved this issue but not sure if it’s the combination of fetch and axios
Any ideas?
Solution
Remove <pre>
tag, and convert it to a json object.
On the server-side just response as a json object instead of a string:
...
const jsonString = response.data.replace(/<\/?pre>/g, '');
res.json(JSON.parse(jsonString)); // instead of res.send(response.data);
...