api post in javascript

To make an API post request in JavaScript, you can use the built-in fetch function or a third-party library like axios. Here are examples of both:

Using fetch:

index.tsx
fetch(url, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(data)
})
  .then(response => response.json())
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error('Error:', error);
  });
265 chars
15 lines

Using axios:

index.tsx
axios.post(url, data, {
  headers: {
    'Content-Type': 'application/json'
  }
})
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error('Error:', error);
  });
204 chars
12 lines

Both functions take three arguments: the URL to send the request to, the data to send in the request body, and an options object that includes any headers or other settings you want to pass. The fetch function returns a promise that you can chain with .then and .catch to handle the response or any errors, while the axios function returns its own promise that you can chain with .then and .catch.

related categories

gistlibby LogSnag