使用以下代码,我试图添加一个新用户,并控制台记录包括新添加的用户在内的所有用户的日志:
const url = "https://jsonplaceholder.typicode.com/users";
// Creating a user
fetch(url, {
method: "POST",
body: JSON.stringify({
name: "Robert Miller",
username: "robby",
email: "roby@outlook.com"
}),
headers: {
Accept: "application/json, text/plain, */*",
"Content-Type": "application/json"
}
})
.then(response => response.json())
.then(response => console.log(response));
但是,console.log仅显示添加的用户,而不显示所有用户。 我的假设是,因为获取方法是POST,所以我需要通过GET发送另一个请求以获取所有用户并提出以下要求:
const url = "https://jsonplaceholder.typicode.com/users";
// Creating a user
fetch(url, {
method: "POST",
body: JSON.stringify({
name: "Robert Miller",
username: "robby",
email: "roby@outlook.com"
}),
headers: {
Accept: "application/json, text/plain, */*",
"Content-Type": "application/json"
}
})
.then(response => response.json())
.then(response => console.log(response));
fetchAllUsers();
function fetchAllUsers() {
fetch(url)
.then(response => {
if (!response.ok) {
throw Error(response.statusText);
}
// Read the response as json.
return response.json();
})
.then(data => {
// Do stuff with the JSON
console.log(data);
})
.catch(error => {
console.log("Looks like there was a problem: \n", error);
});
}
但是我仍然看不到列表中添加的用户。有帮助吗?