fetch发送AJAX请求
1). server.js
//1.引入express
const express = require('express');
//2.创建应用对象
const app = express();
//3.创建路由规则
//request 是对请求报文的封装
//response 是对响应报文的封装
//fetch服务
app.all('/fetch-server', (request, response) => {
//'/server'就相当于一个url
//设置响应头、设置允许跨域
response.setHeader('Access-Control-Allow-Origin', '*')
//设置接收所有相应头
response.setHeader('Access-Control-Allow-Headers','*')
//设置响应体
const data = { name: '尚硅谷' };
response.send(JSON.stringify(data));
});
//4.监听端口启动服务
app.listen(8000, () => {
console.log('服务器已经启动,8000端口监听中...')
})
2). fetch.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>fetch 发送 AJAX请求</title>
</head>
<body>
<button>AJAX请求</button>
</body>
<script>
const btn = document.querySelector('button');
btn.onclick = function(){
//请求参数也是可以直接在url中配置的
fetch('http://127.0.0.1:8000/fetch-server?vip=99',{
//请求方法
method : 'POST',
//请求头
headers:{
a:100,
b:200,
},
//请求体,fetch请求体用的是body
body:{
username:'fetch方法',
pw:'1234567',
}
}).then(response => {
return response.text();
}).then(response =>{
console.log(response);
})
}
</script>
</html>