Home > Back-end >  A function in Appscript that get data from post API
A function in Appscript that get data from post API

Time:12-17

I want to write a function to get a response from an API Like myfunction( url , body)

Then give data as a return

Thanks in advance

Data response Like otp( url, body) Response data ( for example '1234')

CodePudding user response:

How about the built in fetch?

const url = "https://jsonplaceholder.typicode.com/todos";
const payload = { name: "Some name", age: 38 };

fetch(url, {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify(payload),
}).then((res) =>
  res.json().then((response) => {
    console.log(response);
  })
);

CodePudding user response:

I second Paulo's answer.

Another way to write the same thing would be to use async/await:

    const url = 'https://jsonplaceholder.typicode.com/posts';

    const options = {
        method: 'POST',
        headers: {
            'content-type': 'application/json',
        },
        body: JSON.stringify({ 
            userId: '7', 
            title: 'Awesome Post', 
            body: 'Lorem ipsum dolor sit amet...' 
        })
    }

    const fetchData = async () => { // allows for the use of await

        const response = await fetch(url, options);
        const data = await response.json();
        console.log(data);

    }

    fetchData();
  • Related