1.fetch #

2. 发送请求 #

2.1 创建一个新用户(POST请求) #

fetch('http://localhost:3000/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({name: 'New User', age: 20})
})
.then(response => {
  if (!response.ok) {
    throw new Error('HTTP error ' + response.status);
  }
  return response.text();
})
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

2.2 更新用户信息(PUT请求) #

fetch('http://localhost:3000/users?id=1', {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({name: 'Updated User', age: 21})
})
.then(response => {
  if (!response.ok) {
    throw new Error('HTTP error ' + response.status);
  }
  return response.text();
})
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

2.3 查询用户信息(GET请求) #

fetch('http://localhost:3000/users?id=1')
.then(response => {
  if (!response.ok) {
    throw new Error('HTTP error ' + response.status);
  }
  return response.text();
})
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

2.4 删除用户(DELETE请求) #

fetch('http://localhost:3000/users?id=1', {
  method: 'DELETE'
})
.then(response => {
  if (!response.ok) {
    throw new Error('HTTP error ' + response.status);
  }
  return response.text();
})
.then(data => console.log(data))
.catch(error => console.error('Error:', error));