基本使用
fetch(url,options)
.then(response => response.json())
.then(data => console.log(data));
与async ,await结合使用
async function postData(url = '', options= {}) {
const response = await fetch(url, options)
return response.json();
}
postData(url, options)
.then(data => {
console.log(data);
});
写一个简单的request.js文件
function parseJSON(response) {
return response.json();
}
export default async function request(url, options) {
return (
fetch(url, options)
.then(parseJSON)
.then((data) => {
return data;
})
.catch((err) => ({ err }))
);
}
使用示例
import request from "@/utils/request";
export async function getData(param) {
return request(url, {
method: "POST",
body: JSON.stringify(param),
});
}