How can I make a POST request in a VSCode extension

Viewed 1697

I want to make a VSC extension that involves posting to my API, however when I write my fetch syntax out to POST to my server, it doesn't work. So I thought maybe I need to add node-fetch, so I did npm i --save node-fetch and it says This expression is not callable. and once again, it still can't make the POST request.

3 Answers

I have used axios to post to a URL:

import * as FormData from 'form-data';
import axios from 'axios';

          const form = new FormData();
          form.append('srcmbr', save_folderContent.srcmbr);
          form.append('srcfName', save_folderContent.srcfName);
          form.append('srcfLib', save_folderContent.srcfLib);

          const headers = form.getHeaders();
          headers['Content-length'] = await form_getLength(form);
          {
            const result = await axios.post(
              `${serverUrl}/site/common/rmvm-srcmbr.php`, form,
              { headers, });
            console.log(`delete-srcmbr ${result.data}`);
          }
export function form_getLength(form: FormData)
{
  return new Promise((resolve, reject) =>
  {
    form.getLength((err, length) =>
    {
      resolve(length);
    });
  });
}

I forgot to add .default at the end of the axios require.

so it would be

const axios = require('axios').default;

IF YOU'RE USING TYPESCRIPT PLEASE REFER TO @RockBoro 's POST!!!

With node-fetch you can do something like this:

const fetch = require('node-fetch');

async function main () {
  const myUrl = 'https://api.example.com/route';
  const myData = {};

  const response = await fetch(myUrl, {
    method: 'POST',
    body: JSON.stringify(myData),
  }).then((response) => response.json());

  console.log(response);
}
main();
Related