I have written a simple function which works on my local server
index.html
<script>
async function apiCall() {
const url = `/.netlify/functions/hello`;
try {
const response = await fetch(url);
const raw_response= await response;
console.log(await raw_response.status)
const data = await raw_response.json();
console.log(data)
return data;
} catch (err) {
console.log(err);
}
}
apiCall()
</script>
netlify/functions/hello.js
exports.handler = (event, context) => {
return {
statusCode: 200,
body: JSON.stringify('Hola Mundo')
}
}
In the console I see
200
Hola Mundo
However when I deploy to Netlify I see
502
SyntaxError: Unexpected token e in JSON at position 0
https://minimal-net.netlify.app/.netlify/functions/hello
coelmay
2
Hey @psionman
This is not stringifying JSON. You are passing a String (“Hola Mundo”) so it is throwing an error in
For you are returning JSON you would do something like
body: JSON.stringify({ message: "Hola Mundo" })
then in the front end
const data = await raw_response.json()
console.log(data.message) // outputs "Hola Mundo"
If all you wanted to do was return the string “Hola Mundo” you would use
body: "Hola Mundo"
Then as it is not JSON, but text
const response = await fetch(url);
const result = await response.text();
console.log(result) // logs "Hola Mundo"
Check out
Thanks coelmay
(can you not convert a string to json in javascript?)
I have changed my function to
exports.handler = (event, context) => {
return {
statusCode: 200,
body: JSON.stringify({message: "Hola Mundo"})
}
}
and my front end
async function apiCall() {
const url = `/.netlify/functions/hello`;
try {
const response = await fetch(url);
const data = await response.json();
console.log(data.message)
return data;
} catch (err) {
console.log(err);
}
}
apiCall()
It still works on my local server, but deployed, I get
SyntaxError: Unexpected token e in JSON at position 0
I agree, it looks as if body is not jsonified
In fact you can jsonify a string; see:
result = JSON.stringify('abc')
console.log(result)
console.log(JSON.parse(result))
returns
“abc”
abc
In fact the first example in Functions playground is
exports.handler = function (event, context, callback) {
callback(null, {
statusCode: 200,
body: "Hello, World",
});
};
The solution was nothing to do with jsonify. I had missed out the word async in the function
exports.handler = async (event, context) => {
return {
statusCode: 200,
body: JSON.stringify("Hola Mundo")
}
}
1 Like