Hey all:
I am new to functions and am trying to create a POST end route. I have my frontend call setup as so:
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault()
try {
await fetch(`${baseURL}/addResource`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
})
} catch (error: any) {
setErrors([error.message])
}
}
And my function setup as so:
export const handler: Handler = async (event, context) => {
console.log(event.httpMethod)
if (event.httpMethod === "POST") {
const body = event.body && JSON.parse(event.body)
console.log(body) <- undefined in console
try {
//some posting to my Sanity client
return {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Content-Type",
"Access-Control-Allow-Methods": "POST",
},
}
} catch (err) {
return {
statusCode: 500,
body: JSON.stringify({ msg: err.message }),
}
}
} else {
return {
statusCode: 400,
body: JSON.stringify({
message: "Bad Request: Missing prompt in request body",
}),
}
}
}
When I test the function, I am getting ‘OPTIONS’ as the http method logged and so I’m never hitting the post block. Is there another place I need to specify allowed HTTP methods? Thanks in advance!!