我正在寻找一种确定的方法,以使用现代JavaScript框架(例如我的Typescript)处理对REST API的简单HTTP请求,但我想它也适用于Node.js。
由于似乎没有一种简单的本地方法可以执行此操作,所以我发现了很多图书馆,其中有些现已弃用,数十篇可追溯到几年前的文章根据最新的最佳实践进行了更新。当然,可以这么难。这需要我大约5分钟的时间才能在Golang或Python中实现,但是遗憾的是使用JavaScript很难-是我吗?
请问有人根据我们现在的情况2020年,阐明目前的比赛状态和推荐方法。
答案 0 :(得分:1)
尽管request-promise-native可能工作得很好,但Axios是在TypeScript中使用的一种更好的替代方法。它带有自己的类型定义,总体上对其他程序包的依赖性较小。使用它的API非常类似于Adrian提供的答案,但是有一些细微的差异。
const url: string = 'your-url.example';
try {
const response = await axios.get(yourUrl);
} catch (exception) {
process.stderr.write(`ERROR received from ${url}: ${exception}\n`);
}
答案 1 :(得分:0)
结帐https://www.npmjs.com/package/node-fetch和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);
});
答案 2 :(得分:0)
看看Microsoft正式支持的light lib typed-rest-client