如何用fetch发动post申请

上面是一个用fetch发动的post申请示例:

fetch('/api/add', {  method: 'POST',  headers: {    'Content-Type': 'application/json',  },  body: JSON.stringify({    name: 'tomcat',  }),}).then(res => res.json()).then(res => {  console.log('res', res);});

注意事项:

如何传递post参数?

  1. 设置Content-Typeapplication/json
  2. post参数转换为字符串,须要用到JSON.stringify

如何解析响应?

须要对fetch返回的响应调用json办法。

因为fetch返回的是一个Response对象,不能间接读取数据,所以须要对其先调用一下json办法,而后能力失去冀望的数据对象。