Javascript 使用 Async/Await 使 API 获取“POST”的正确方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50046841/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Proper Way to Make API Fetch 'POST' with Async/Await
提问by Nik Ackermann
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?
我正在处理一个需要我向 API 发出请求的项目。使用 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.
例如,这是我获取所有设备列表的方法。我将如何将此请求更改为 POST 以创建新设备?我知道我必须添加一个带有数据体的标题。
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;
};
回答by Prince Hernandez
actually your code can be improved like this:
实际上你的代码可以这样改进:
to do a post just add the method on the settings of the fetch call.
做一个帖子只需在 fetch 调用的设置上添加方法。
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;
}
}
回答by Ali Ankarali
Here is an example with configuration:
这是一个配置示例:
try {
const config = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(data)
}
const response = await fetch(url, config)
//const json = await response.json()
if (response.ok) {
//return json
return response
} else {
//
}
} catch (error) {
//
}
回答by TomasVeras
Remember to avoid to combine async/awaitand thenhere is an example:
请记住避免组合async/await,then这是一个示例:
const addDevice = async (device) => {
const { hostname: location } = window.location;
const settings = {
method: 'POST',
body: JSON.stringify(device),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
}
const response = await fetch(`http://${location}:9000/api/sensors/`, settings);
if (!response.ok) throw Error(response.message);
try {
const data = await response.json();
return data;
} catch (err) {
throw err;
}
};

