我想写一个函数来从API获取响应
像myfunction(url, body)
给出数据作为返回
数据响应
如otp(url, body)
响应数据(例如'1234')
内置取回功能如何?
const url = "https://jsonplaceholder.typicode.com/todos";
const payload = { name: "Some name", age: 38 };
fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
}).then((res) =>
res.json().then((response) => {
console.log(response);
})
);
我同意保罗的回答。
另一种写法是使用async/await:const url = 'https://jsonplaceholder.typicode.com/posts';
const options = {
method: 'POST',
headers: {
'content-type': 'application/json',
},
body: JSON.stringify({
userId: '7',
title: 'Awesome Post',
body: 'Lorem ipsum dolor sit amet...'
})
}
const fetchData = async () => { // allows for the use of await
const response = await fetch(url, options);
const data = await response.json();
console.log(data);
}
fetchData();