Ajax--使用fetch函数发送AJAX请求

1.使用fetch函数发送AJAX请求 参考文档: 1.1 请求前的准备 1.1.1 HTML页面 ajaxDemo.html DOCTYPE html>

1.使用fetch函数发送AJAX请求

参考文档:


1.1 请求前的准备


1.1.1 HTML页面

在这里插入图片描述
ajaxDemo.html

DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>fetch 发送 AJAX请求title>
head>
<body>
<button>AJAX请求button>
<script>
script>
body>
html>

在这里插入图片描述


1.1.2 服务端

在这里插入图片描述
server.js

//1. 引入express
const express = require('express');//2. 创建应用对象
const app = express();//3. 创建路由规则
// request 是对请求报文的封装
// response 是对响应报文的封装//fetch 服务
app.all('/fetch-server', (request, response) => {//设置响应头  设置允许跨域response.setHeader('Access-Control-Allow-Origin', '*');//允许自定义请求头标签response.setHeader('Access-Control-Allow-Headers', '*');// response.send('Hello jQuery AJAX');const data = {name: '🥩🥩🥩'};response.send(JSON.stringify(data));
});//4. 监听端口启动服务
app.listen(8000, () => {console.log("服务已经启动, 8000 端口监听中....");
});

启动服务端:

在这里插入图片描述在这里插入图片描述


1.2 使用fetch函数发送AJAX请求

ajaxDemo.html中script标签的代码

const btn = document.querySelector('button');btn.onclick = function () {fetch('http://127.0.0.1:8000/fetch-server?vip=10', {//请求方法method: 'POST',//请求头headers: {name: 'atguigu'},//请求体body: 'username=admin&password=admin'}).then(response => {// return response.text();return response.json();}).then(response => {console.log(response);});}

结果:

在这里插入图片描述