从开始到现在, 调用API的方式也变了很多
- 最开始接触的是xmlHttpRequest
- 后来接触到ajax请求
- 工作之后, 开始使用fetch请求
- 学习了node.js之后, 发现在node.js中发起fetch请求, 需要引入node-fetch包.
https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch
一个简单的fetch请求
- 需要URL, 也就是请求的位置
- HTTP请求有几大类, 常用的是Get和POST请求
- 请求的时候需要考虑跨域, 也就是要设置mode是不是cors
- 请求的缓存设置cache
- 请求的header是个对象, 可以设置content-type, 一般是application/json
- 请求的body里面是post的参数
- 最后请求返还的是一个promise对象, 要使用.then()获取成功返回的数据, 使用.catch()拿到返回的错误.
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return response.json();