Supabase Edge function says no body was passed - javascript

I'm invoking a supabase edge function with the following
async function getData(plan_data){
console.log(plan_data)
console.log(JSON.stringify({plan_data}))
const { data, error } = await supabase.functions.invoke("create-stripe-checkout",
{
body: JSON.stringify({
plan_data
}),
}
)
console.log(data, error)
// console.log(data)
}
In the edge function I console logged the request and it stated bodyUsed: false. Essentially the edge function acts like and believes that no value was passed. (A value is passed to the getData function properly).I've played around with the syntax a bit to no avail, am I missing something?
EDIT:
Edge function is as follows
import { serve } from "https://deno.land/std#0.131.0/http/server.ts"
serve(async (req) => {
if (req.method === "OPTIONS"){
return new Response (null, {
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "apikey, X-Client-Info, Authorization, content-type",
}
})
}
console.log(req)
const { planId } = await req.json()
console.log(planId)
return new Response(
JSON.stringify({ planId }),
{ headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "apikey, X-Client-Info, Authorization, content-type",
// "Content-Type": "application/json",
} },
)
})
EDIT: I tried running it with supabase's example code and had the same issue.

Seeing how this was a CORS error, I ended up allowing all headers in the preflight check response CORS headers.
I.e.
...
if (req.method === "OPTIONS"){
return new Response (null, {
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "*", // <-- change here
}
})
}
...

Does adding the content type header work?
async function getData(plan_data) {
console.log(plan_data)
console.log(JSON.stringify({ plan_data }))
const { data, error } = await supabase.functions.invoke("create-stripe-checkout",
{
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
plan_data
}),
});
console.log(data, error)
}

Supabase SDK will take care of json encoding, so you don't need to do it by yourself.
async function getData(plan_data){
const { data, error } = await supabase.functions.invoke("create-stripe-checkout",
{
body: { plan_data },
}
)
console.log(data, error)
}
You should be able to get the data on your Edge Function like this:
const { plan_data } = await req.json()
console.log(plan_data)

Related

Get Reponse Code and JSON Response in Fetch

I have following Code to get the Response from the API. Now I want a response if the data are successfully send to the server. My first idea was to do it with the response code. If it is 200 it is successfull. The other idea is, to make it with a try catch statement.
public async daten_eintragen(): Promise<void> {
// try {
const headers = {
"Access-Control-Allow-Origin": "localhost",
"Access-Control-Allow-Methods": "OPTIONS, GET, POST, PUT, PATCH, DELETE",
};
const jsondata = {
proasdftName: "tfghtdsddskt",
pauctasdfsion: "this.csdfgudfghrrentItemVersio",
cosdfasdftName: "mardfddsdfgfdfbvdfdasdfumfghjann",
vdon: "this.currentItesdfghdfmVersion",
vedor: "this.currentsdfgItemVendor",
lde: "this.currentsdfdfgItemFrdgfhamework",
proepage: "this.csdfgurrentItedfghmHomepage",
nType: "this.cursdfgrentItedfghmIntegration",
upe: "this.currentItsdfgfdghemUsage",
sL: "this.currentItemSsdfgourcfgheCodeAnpassungen",
};
console.log(this.currentItemName);
fetch(this.appConf.apiBaseUrl + "compon", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify(jsondata),
}).then(async (response) => {
// get json response here
let data = await response.json();
console.log(data);
});
}
Getting the response from the server it was successful.
Looking at the response properties you can simply check response.ok. Something like this:
fetch(this.appConf.apiBaseUrl + "compon", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify(jsondata),
}).then(async (response) => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
console.log("request was successfull. Proceeding with extracting data");
// get json response here
let data = await response.json();
console.log("data", data);
}).catch(e => {
console.log('An error occurred', e);
});

Catch Google Cloud function errors in POST

I have this cloud function that append a line to a Google Spreadsheet:
function addLine(req, res) {
res.set("Access-Control-Allow-Origin", "*");
if (req.method === "OPTIONS") {
res.set("Access-Control-Allow-Methods", "POST");
res.set("Access-Control-Allow-Headers", "Content-Type");
res.set("Access-Control-Max-Age", "3600");
return res.status(204).send("");
}
const isReqValid = validateReq(req);
if (!isReqValid) return res.send("Not valid request!"); // <--
const { body } = req;
const isBodyValid = validateData(body);
if (!isBodyValid) return res.send("Not valid payload!"); // <--
return appendData(body)
.then(() => res.send("Added line"))
.catch((err) => {
res.send("Generic error!");
});
}
function validateReq(req) {
if (req.method !== "POST") return false;
return true;
}
function validateData(data) {
// do something and return true or false
}
async function appendData(data) {
const client = await auth.getClient();
return sheets.spreadsheets.values.append(
{
spreadsheetId: ...,
auth: client,
range: "A1:B",
valueInputOption: "RAW",
resource: { values: [data] },
},
);
}
I use it in this way:
async collaborate(data: CollaborateDatum) {
await post('...cloudfunctions.net/addLine', data)
}
async function post(url, data) {
return fetch(url, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
}
How can I "read" the errors Not valid request! and Not valid payload!? Because if I tried to append a line with not valid data, I get status code 200 but in Chrome Dev Tools -> Network -> Response, the response is Not valid payload! but I don't know how to catch this error.
Thanks a lot!
You should be able to get any response text that's passed back like this:
let responseText = await (await post('...cloudfunctions.net/addLine', data)).text();

How to set CORS in Cloudflare Workers?

I'm a newbie in Cloudflare Workers.
How to set CORS in Cloudflare Workers?
response = await cache.match(cacheKey);
if (!response) {
// handle fetch data and cache
}
const myHeaders = new Headers();
myHeaders.set("Access-Control-Allow-Origin", event.request.headers.get("Origin"));
return new Response(JSON.stringify({
response
}), {
status: 200, headers: myHeaders
});
It's quite a pain actually. There is a sample from Cloudflare, but it can't be used directly. I finally worked it out recently, and put the detailed steps into a
blog post.
Here is the full code for the worker.
// Reference: https://developers.cloudflare.com/workers/examples/cors-header-proxy
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET,HEAD,POST,OPTIONS",
"Access-Control-Max-Age": "86400",
}
function handleOptions (request) {
// Make sure the necessary headers are present
// for this to be a valid pre-flight request
let headers = request.headers
if (
headers.get("Origin") !== null &&
headers.get("Access-Control-Request-Method") !== null &&
headers.get("Access-Control-Request-Headers") !== null
) {
// Handle CORS pre-flight request.
// If you want to check or reject the requested method + headers
// you can do that here.
let respHeaders = {
...corsHeaders,
// Allow all future content Request headers to go back to browser
// such as Authorization (Bearer) or X-Client-Name-Version
"Access-Control-Allow-Headers": request.headers.get("Access-Control-Request-Headers"),
}
return new Response(null, {
headers: respHeaders,
})
}
else {
// Handle standard OPTIONS request.
// If you want to allow other HTTP Methods, you can do that here.
return new Response(null, {
headers: {
Allow: "GET, HEAD, POST, OPTIONS",
},
})
}
}
async function handleRequest (request) {
let response
if (request.method === "OPTIONS") {
response = handleOptions(request)
}
else {
response = await fetch(request)
response = new Response(response.body, response)
response.headers.set("Access-Control-Allow-Origin", "*")
response.headers.set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
}
return response
}
addEventListener("fetch", (event) => {
event.respondWith(
handleRequest(event.request).catch(
(err) => new Response(err.stack, { status: 500 })
)
);
});
Your code does not set the Content-Type header. You should either set it with myHeaders.set() or use the original response headers instead of creating an empty headers object:
response = await cache.match(cacheKey);
if (!response) {
// handle fetch data and cache
}
const myHeaders = new Headers(response.headers);
myHeaders.set("Access-Control-Allow-Origin", event.request.headers.get("Origin"));
I'm also questioning why you are trying to use JSON.stringify on the response. I think what you want is something like this:
return new Response(response.body, {status: 200, headers: myHeaders});
Here's how got it working. I'm using Itty Router but this should work the same for a normal worker as well.
router.get("/data", async (request) => {
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, OPTIONS",
"Access-Control-Allow-Headers": "*",
};
if (request.method.toLowerCase() === "options") {
return new Response("ok", {
headers: corsHeaders,
});
}
try {
const data = await getData();
return new Response(data, {
headers: {
"Content-Type": "application/json",
// don't forget this.👇🏻 You also need to send back the headers with the actual response
...corsHeaders,
},
});
} catch (error) {}
return new Response(JSON.stringify([]), {
headers: corsHeaders,
});
});
Thanks to this Free Egghead video Add CORS Headers to a Third Party API Response in a Workers API
Anurag's answer got me 90% of the way there, thank you for that. I'm using itty-router as well, here's what I had to add.
I created a simple preflight middleware:
const corsHeaders = {
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Origin': '*',
};
export const withCorsPreflight = (request: Request) => {
if (request.method.toLowerCase() === 'options') {
return new Response('ok', {
headers: corsHeaders,
});
}
};
I then added it to every route.
router.all('*', withCorsPreflight);
router.get('/api/another-route', handler);
Hope this helps!

Put request with simple string as request body

When I execute the following code from my browser the server gives me 400 and complains that the request body is missing. Anybody got a clue about how I can pass a simple string and have it send as the request body?
let content = 'Hello world'
axios.put(url, content).then(response => {
resolve(response.data.content)
}, response => {
this.handleEditError(response)
})
If I wrap content in [] it comes thru. But then the server receives it as a string beginning with [ and ending with ]. Which seems odd.
After fiddling around I discovered that the following works
let req = {
url,
method: 'PUT',
data: content
}
axios(req).then(response => {
resolve(response.data.content)
}, response => {
this.handleEditError(response)
})
But shouldn't the first one work as well?
I solved this by overriding the default Content-Type:
const config = { headers: {'Content-Type': 'application/json'} };
axios.put(url, content, config).then(response => {
...
});
Based on my experience, the default Content-Type is application/x-www-form-urlencoded for strings, and application/json for objects (including arrays). Your server probably expects JSON.
This works for me (code called from node js repl):
const axios = require("axios");
axios
.put(
"http://localhost:4000/api/token",
"mytoken",
{headers: {"Content-Type": "text/plain"}}
)
.then(r => console.log(r.status))
.catch(e => console.log(e));
Logs: 200
And this is my request handler (I am using restify):
function handleToken(req, res) {
if(typeof req.body === "string" && req.body.length > 3) {
res.send(200);
} else {
res.send(400);
}
}
Content-Type header is important here.
I was having trouble sending plain text and found that I needed to surround the body's value with double quotes:
const request = axios.put(url, "\"" + values.guid + "\"", {
headers: {
"Accept": "application/json",
"Content-type": "application/json",
"Authorization": "Bearer " + sessionStorage.getItem('jwt')
}
})
My webapi server method signature is this:
public IActionResult UpdateModelGuid([FromRoute] string guid, [FromBody] string newGuid)
Have you tried the following:
axios.post('/save', { firstName: 'Marlon', lastName: 'Bernardes' })
.then(function(response){
console.log('saved successfully')
});
Reference: http://codeheaven.io/how-to-use-axios-as-your-http-client/
axios.put(url,{body},{headers:{}})
example:
const body = {title: "what!"}
const api = {
apikey: "safhjsdflajksdfh",
Authorization: "Basic bwejdkfhasjk"
}
axios.put('https://api.xxx.net/xx', body, {headers: api})
simply put in headers 'Content-Type': 'application/json' and the sent data in body JSON.stringify(string)
Another simple solution is to surround the content variable in your given code with braces like this:
let content = 'Hello world'
axios.put(url, {content}).then(response => {
resolve(response.data.content)
}, response => {
this.handleEditError(response)
})
Caveat: But this will not send it as string; it will wrap it in a json body that will look like this: {content: "Hello world"}
This worked for me:
export function modalSave(name,id){
console.log('modalChanges action ' + name+id);
return {
type: 'EDIT',
payload: new Promise((resolve, reject) => {
const value = {
Name: name,
ID: id,
}
axios({
method: 'put',
url: 'http://localhost:53203/api/values',
data: value,
config: { headers: {'Content-Type': 'multipart/form-data' }}
})
.then(function (response) {
if (response.status === 200) {
console.log("Update Success");
resolve();
}
})
.catch(function (response) {
console.log(response);
resolve();
});
})
};
}
this worked for me.
let content = 'Hello world';
static apicall(content) {
return axios({
url: `url`,
method: "put",
data: content
});
}
apicall()
.then((response) => {
console.log("success",response.data)
}
.error( () => console.log('error'));

Fetch: POST JSON data

I'm trying to POST a JSON object using fetch.
From what I can understand, I need to attach a stringified object to the body of the request, e.g.:
fetch("/echo/json/",
{
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "POST",
body: JSON.stringify({a: 1, b: 2})
})
.then(function(res){ console.log(res) })
.catch(function(res){ console.log(res) })
When using jsfiddle's JSON echo I'd expect to see the object I've sent ({a: 1, b: 2}) back, but this does not happen - chrome devtools doesn't even show the JSON as part of the request, which means that it's not being sent.
With ES2017 async/await support, this is how to POST a JSON payload:
(async () => {
const rawResponse = await fetch('https://httpbin.org/post', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({a: 1, b: 'Textual content'})
});
const content = await rawResponse.json();
console.log(content);
})();
Can't use ES2017? See #vp_art's answer using promises
The question however is asking for an issue caused by a long since fixed chrome bug.
Original answer follows.
chrome devtools doesn't even show the JSON as part of the request
This is the real issue here, and it's a bug with chrome devtools, fixed in Chrome 46.
That code works fine - it is POSTing the JSON correctly, it just cannot be seen.
I'd expect to see the object I've sent back
that's not working because that is not the correct format for JSfiddle's echo.
The correct code is:
var payload = {
a: 1,
b: 2
};
var data = new FormData();
data.append( "json", JSON.stringify( payload ) );
fetch("/echo/json/",
{
method: "POST",
body: data
})
.then(function(res){ return res.json(); })
.then(function(data){ alert( JSON.stringify( data ) ) })
For endpoints accepting JSON payloads, the original code is correct
I think your issue is jsfiddle can process form-urlencoded request only. But correct way to make json request is pass correct json as a body:
fetch('https://httpbin.org/post', {
method: 'POST',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify({a: 7, str: 'Some string: &=&'})
}).then(res => res.json())
.then(res => console.log(res));
From search engines, I ended up on this topic for non-json posting data with fetch, so thought I would add this.
For non-json you don't have to use form data. You can simply set the Content-Type header to application/x-www-form-urlencoded and use a string:
fetch('url here', {
method: 'POST',
headers: {'Content-Type':'application/x-www-form-urlencoded'}, // this line is important, if this content-type is not set it wont work
body: 'foo=bar&blah=1'
});
An alternative way to build that body string, rather then typing it out as I did above, is to use libraries. For instance the stringify function from query-string or qs packages. So using this it would look like:
import queryString from 'query-string'; // import the queryString class
fetch('url here', {
method: 'POST',
headers: {'Content-Type':'application/x-www-form-urlencoded'}, // this line is important, if this content-type is not set it wont work
body: queryString.stringify({for:'bar', blah:1}) //use the stringify object of the queryString class
});
After spending some times, reverse engineering jsFiddle, trying to generate payload - there is an effect.
Please take eye (care) on line return response.json(); where response is not a response - it is promise.
var json = {
json: JSON.stringify({
a: 1,
b: 2
}),
delay: 3
};
fetch('/echo/json/', {
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: 'json=' + encodeURIComponent(JSON.stringify(json.json)) + '&delay=' + json.delay
})
.then(function (response) {
return response.json();
})
.then(function (result) {
alert(result);
})
.catch (function (error) {
console.log('Request failed', error);
});
jsFiddle: http://jsfiddle.net/egxt6cpz/46/ && Firefox > 39 && Chrome > 42
2021 answer: just in case you land here looking for how to make GET and POST Fetch api requests using async/await or promises as compared to axios.
I'm using jsonplaceholder fake API to demonstrate:
Fetch api GET request using async/await:
const asyncGetCall = async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
const data = await response.json();
// enter you logic when the fetch is successful
console.log(data);
} catch(error) {
// enter your logic for when there is an error (ex. error toast)
console.log(error)
}
}
asyncGetCall()
Fetch api POST request using async/await:
const asyncPostCall = async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
// your expected POST request payload goes here
title: "My post title",
body: "My post content."
})
});
const data = await response.json();
// enter you logic when the fetch is successful
console.log(data);
} catch(error) {
// enter your logic for when there is an error (ex. error toast)
console.log(error)
}
}
asyncPostCall()
GET request using Promises:
fetch('https://jsonplaceholder.typicode.com/posts')
.then(res => res.json())
.then(data => {
// enter you logic when the fetch is successful
console.log(data)
})
.catch(error => {
// enter your logic for when there is an error (ex. error toast)
console.log(error)
})
POST request using Promises:
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
// your expected POST request payload goes here
title: "My post title",
body: "My post content."
})
})
.then(res => res.json())
.then(data => {
// enter you logic when the fetch is successful
console.log(data)
})
.catch(error => {
// enter your logic for when there is an error (ex. error toast)
console.log(error)
})
GET request using Axios:
const axiosGetCall = async () => {
try {
const { data } = await axios.get('https://jsonplaceholder.typicode.com/posts')
// enter you logic when the fetch is successful
console.log(`data: `, data)
} catch (error) {
// enter your logic for when there is an error (ex. error toast)
console.log(`error: `, error)
}
}
axiosGetCall()
POST request using Axios:
const axiosPostCall = async () => {
try {
const { data } = await axios.post('https://jsonplaceholder.typicode.com/posts', {
// your expected POST request payload goes here
title: "My post title",
body: "My post content."
})
// enter you logic when the fetch is successful
console.log(`data: `, data)
} catch (error) {
// enter your logic for when there is an error (ex. error toast)
console.log(`error: `, error)
}
}
axiosPostCall()
I have created a thin wrapper around fetch() with many improvements if you are using a purely json REST API:
// Small library to improve on fetch() usage
const api = function(method, url, data, headers = {}){
return fetch(url, {
method: method.toUpperCase(),
body: JSON.stringify(data), // send it as stringified json
credentials: api.credentials, // to keep the session on the request
headers: Object.assign({}, api.headers, headers) // extend the headers
}).then(res => res.ok ? res.json() : Promise.reject(res));
};
// Defaults that can be globally overwritten
api.credentials = 'include';
api.headers = {
'csrf-token': window.csrf || '', // only if globally set, otherwise ignored
'Accept': 'application/json', // receive json
'Content-Type': 'application/json' // send json
};
// Convenient methods
['get', 'post', 'put', 'delete'].forEach(method => {
api[method] = api.bind(null, method);
});
To use it you have the variable api and 4 methods:
api.get('/todo').then(all => { /* ... */ });
And within an async function:
const all = await api.get('/todo');
// ...
Example with jQuery:
$('.like').on('click', async e => {
const id = 123; // Get it however it is better suited
await api.put(`/like/${id}`, { like: true });
// Whatever:
$(e.target).addClass('active dislike').removeClass('like');
});
Had the same issue - no body was sent from a client to a server.
Adding Content-Type header solved it for me:
var headers = new Headers();
headers.append('Accept', 'application/json'); // This one is enough for GET requests
headers.append('Content-Type', 'application/json'); // This one sends body
return fetch('/some/endpoint', {
method: 'POST',
mode: 'same-origin',
credentials: 'include',
redirect: 'follow',
headers: headers,
body: JSON.stringify({
name: 'John',
surname: 'Doe'
}),
}).then(resp => {
...
}).catch(err => {
...
})
This is related to Content-Type. As you might have noticed from other discussions and answers to this question some people were able to solve it by setting Content-Type: 'application/json'. Unfortunately in my case it didn't work, my POST request was still empty on the server side.
However, if you try with jQuery's $.post() and it's working, the reason is probably because of jQuery using Content-Type: 'x-www-form-urlencoded' instead of application/json.
data = Object.keys(data).map(key => encodeURIComponent(key) + '=' + encodeURIComponent(data[key])).join('&')
fetch('/api/', {
method: 'post',
credentials: "include",
body: data,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
The top answer doesn't work for PHP7, because it has wrong encoding, but I could figure the right encoding out with the other answers. This code also sends authentication cookies, which you probably want when dealing with e.g. PHP forums:
julia = function(juliacode) {
fetch('julia.php', {
method: "POST",
credentials: "include", // send cookies
headers: {
'Accept': 'application/json, text/plain, */*',
//'Content-Type': 'application/json'
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" // otherwise $_POST is empty
},
body: "juliacode=" + encodeURIComponent(juliacode)
})
.then(function(response) {
return response.json(); // .text();
})
.then(function(myJson) {
console.log(myJson);
});
}
It might be useful to somebody:
I was having the issue that formdata was not being sent for my request
In my case it was a combination of following headers that were also causing the issue and the wrong Content-Type.
So I was sending these two headers with the request and it wasn't sending the formdata when I removed the headers that worked.
"X-Prototype-Version" : "1.6.1",
"X-Requested-With" : "XMLHttpRequest"
Also as other answers suggest that the Content-Type header needs to be correct.
For my request the correct Content-Type header was:
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
So bottom line if your formdata is not being attached to the Request then it could potentially be your headers. Try bringing your headers to a minimum and then try adding them one by one to see if your problem is resolved.
If your JSON payload contains arrays and nested objects, I would use URLSearchParams and jQuery's param() method.
fetch('/somewhere', {
method: 'POST',
body: new URLSearchParams($.param(payload))
})
To your server, this will look like a standard HTML <form> being POSTed.
You could do it even better with await/async.
The parameters of http request:
const _url = 'https://jsonplaceholder.typicode.com/posts';
let _body = JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1,
});
const _headers = {
'Content-type': 'application/json; charset=UTF-8',
};
const _options = { method: 'POST', headers: _headers, body: _body };
With clean async/await syntax:
const response = await fetch(_url, _options);
if (response.status >= 200 && response.status <= 204) {
let data = await response.json();
console.log(data);
} else {
console.log(`something wrong, the server code: ${response.status}`);
}
With old fashion fetch().then().then():
fetch(_url, _options)
.then((res) => res.json())
.then((json) => console.log(json));
**//POST a request**
const createTodo = async (todo) => {
let options = {
method: "POST",
headers: {
"Content-Type":"application/json",
},
body: JSON.stringify(todo)
}
let p = await fetch("https://jsonplaceholder.typicode.com/posts", options);
let response = await p.json();
return response;
}
**//GET request**
const getTodo = async (id) => {
let response = await fetch('https://jsonplaceholder.typicode.com/posts/' + id);
let r = await response.json();
return r;
}
const mainFunc = async () => {
let todo = {
title: "milan7",
body: "dai7",
userID: 101
}
let todor = await createTodo(todo);
console.log(todor);
console.log(await getTodo(5));
}
mainFunc()
I think that, we don't need parse the JSON object into a string, if the remote server accepts json into they request, just run:
const request = await fetch ('/echo/json', {
headers: {
'Content-type': 'application/json'
},
method: 'POST',
body: { a: 1, b: 2 }
});
Such as the curl request
curl -v -X POST -H 'Content-Type: application/json' -d '#data.json' '/echo/json'
In case to the remote serve not accept a json file as the body, just send a dataForm:
const data = new FormData ();
data.append ('a', 1);
data.append ('b', 2);
const request = await fetch ('/echo/form', {
headers: {
'Content-type': 'application/x-www-form-urlencoded'
},
method: 'POST',
body: data
});
Such as the curl request
curl -v -X POST -H 'Content-type: application/x-www-form-urlencoded' -d '#data.txt' '/echo/form'
You only need to check if response is ok coz the call not returning anything.
var json = {
json: JSON.stringify({
a: 1,
b: 2
}),
delay: 3
};
fetch('/echo/json/', {
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: 'json=' + encodeURIComponent(JSON.stringify(json.json)) + '&delay=' + json.delay
})
.then((response) => {if(response.ok){alert("the call works ok")}})
.catch (function (error) {
console.log('Request failed', error);
});
// extend FormData for direct use of js objects
Object.defineProperties(FormData.prototype, {
load: {
value: function (d) {
for (var v in d) {
this.append(v, typeof d[v] === 'string' ? d[v] : JSON.stringify(d[v]));
}
}
}
})
var F = new FormData;
F.load({A:1,B:2});
fetch('url_target?C=3&D=blabla', {
method: "POST",
body: F
}).then( response_handler )
you can use fill-fetch, which is an extension of fetch. Simply, you can post data as below:
import { fill } from 'fill-fetch';
const fetcher = fill();
fetcher.config.timeout = 3000;
fetcher.config.maxConcurrence = 10;
fetcher.config.baseURL = 'http://www.github.com';
const res = await fetcher.post('/', { a: 1 }, {
headers: {
'bearer': '1234'
}
});

Categories

Resources