效果展示:
功能:
点击AJAX按钮,使用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>ajax fetch发送请求</title>
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link crossorigin="anonymous" rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu">
<script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/axios/0.26.0/axios.js"></script>
</head>
<body>
<div class="container">
<h2 class="page-header">fetch发送AJAX请求</h2>
<button type="button" class="btn btn-info">AJAX</button>
</div>
<script>
btn = document.querySelector('button');
btn.onclick = function(){
fetch('http:127.0.0.1:8000/fetch-server',{
// 请求方法
method: 'POST',
// 请求头
headers: {
name: 'admin'
},
// 请求体
body: 'uname=aaa&password=aaa'
}).then(response => {
return response.json();
}).then(response => {
console.log(response);
});
};
</script>
</body>
</html>
JS:
// 引入
const { request } = require('express');
// 创建应用对象
const express = require('express');
// 创建应用对象
const app = express();
// 创建路由规则
app.all('/fetch-server',(request,response) => {
// 设置响应头 设置允许跨域
response.setHeader('Access-Control-Allow-Origin','*');
response.setHeader('Access-Control-Allow-Headers','*');
const data = {name: 'xxx'};
// 设置响应体
response.send(JSON.stringify(data));
});
// 监听端口启动服务
app.listen(8000,() => {
console.log("服务已启动,8000端口监听中...");
})