我正在从事一个需要我向 API 发出请求的项目。使用 Async/Await 发出 POST
请求的正确形式是什么?
例如,这是我获取所有设备列表的请求。我将如何将此请求更改为 POST
以创建新设备?我知道我必须添加带有数据主体的 header 。
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;
};
最佳答案
实际上你的代码可以这样改进:
要发布文章,只需在获取调用的设置中添加方法即可。
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;
}
}
关于javascript - 使用 Async/Await 获取 API 'POST' 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50046841/