N
Nuxt2y ago
dmarr

Making POST or PATCH requests with $fetch?

I would like to send a request to an external API using $fetch. I am getting some errors when doing something like so:
body = await readBody(event);
headers = { authorization: 'foo' }
$fetch('https://foo.com/api', { body, headers, method: 'POST' })
body = await readBody(event);
headers = { authorization: 'foo' }
$fetch('https://foo.com/api', { body, headers, method: 'POST' })
The response from the server is "invalid JSON". I am inspecting the request before it goes out and it looks like a valid object.
1 Reply
dmarr
dmarrOP2y ago
According to ofetch, the json content-type and stringification of body happens automatically
Payload validation error: 'Expected type object but found type string'.
I guess you still have to stringify the body Actually seems to be a bug in ofetch https://github.com/unjs/ofetch/issues/208 oh, i guess it's because i'm using a URL object, not a string for the first argument to $fetch. calling toString on it fixes the issue I should have listened to TypeScript!
Argument of type 'URL' is not assignable to parameter of type 'NitroFetchRequest'.
Thing is, we should be using the platform better.. This works funnily enough
function onRequest(e) {
e.request = e.request.toString();
}
function onRequest(e) {
e.request = e.request.toString();
}
Want results from more Discord servers?
Add your server