简体   繁体   中英

Making HTTP requests using Typescript or NodeJS

I'm looking for a definitive way to handle simple HTTP requests to a REST API using modern javascript frameworks, in my case Typescript but I guess it would also apply to Nodejs.

Since there doesn't seem to be a simple native way to do this, I have found a plethora of libraries, some now deprecated and dozen's of articles dating back several years some with updates based on the newer best practises. Surely it can't be that hard. This takes me about 5mins to implement in Golang or Python, but alas with JavaScript its a pain - Is it just me?

Could somebody please clarify the current state of play and recommended way to do this based on where we are now in 2020.

Even though request-promise-native probably works just fine, Axios is a way better alternative for use in TypeScript. It comes with its own type definitions and is overall less dependent on other packages. Using it's API is quite like the answer provided by Adrian, however there are a few subtle differences.

const url: string = 'your-url.example';

try {
    const response = await axios.get(yourUrl);
} catch (exception) {
    process.stderr.write(`ERROR received from ${url}: ${exception}\n`);
}

Do checkout https://www.npmjs.com/package/node-fetch and https://www.npmjs.com/package/axios

    // using axios
const options = {
  url: 'http://localhost/test.htm',
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json;charset=UTF-8'
  },
  data: {
    a: 10,
    b: 20
  }
};

axios(options)
  .then(response => {
    console.log(response.status);
  });



//using fetch
const url = 'http://localhost/test.htm';
const options = {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json;charset=UTF-8'
  },
  body: JSON.stringify({
    a: 10,
    b: 20
  })
};

fetch(url, options)
  .then(response => {
    console.log(response.status);
  });

Look at the light lib typed-rest-client officially supported by Microsoft

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM