使API通过Async/Await提取"POST"的正确方法 [英] Proper Way to Make API Fetch 'POST' with Async/Await
本文介绍了使API通过Async/Await提取"POST"的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在研究一个需要我向API发出请求的项目.用Async/Await发出POST请求的正确形式是什么?
I'm working on a project that requires me to make requests to an API. What is the proper form for making a POST request with Async/Await?
作为一个例子,这是我获取所有设备列表的信息.我将如何将此请求更改为POST以创建新设备?我知道我必须添加带有数据正文的标头.
As an example, here is my fetch to get a list of all devices. How would I go about changing this request to POST to create a new device? I understand I would have to add a header with a data body.
getDevices = async () => {
const location = window.location.hostname;
const response = await fetch(
`http://${location}:9000/api/sensors/`
);
const data = await response.json();
if (response.status !== 200) throw Error(data.message);
return data;
};
推荐答案
实际上,您的代码可以像这样进行改进:
actually your code can be improved like this:
要做一个帖子,只需在fetch调用的设置上添加方法.
to do a post just add the method on the settings of the fetch call.
getDevices = async () => {
const location = window.location.hostname;
const settings = {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
}
};
try {
const fetchResponse = await fetch(`http://${location}:9000/api/sensors/`, settings);
const data = await fetchResponse.json();
return data;
} catch (e) {
return e;
}
}
这篇关于使API通过Async/Await提取"POST"的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文