Appearance
fetch
fetch 在html代码中 post请求的简单应用
html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>fetch</title>
</head>
<body>
<script>
async function xysPostFetch(url, data = {}){
let options = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`HTTP错误-状态码-${response.status}`);
}
return await response.json();
}
async function start(){
try {
let resData = await xysPostFetch('https://jsonplaceholder.typicode.com/posts', {aaa: 'bbb'})
console.log(resData)
} catch (e) {
console.error('出错了', e.message)
}
}
start();
</script>
</body>
</html>