Use the fetch function to send ajax

Back to the general list of articles

Use fetch function to send ajax request
MDN document address
Chinese document
https://developer.mozilla.org/zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/fetch
English document
https://developer.mozilla.org/en-US/ docs/Web/API/WindowOrWorkerGlobalScope/fetch

In this page, there 看英文文档is a problem with the translation of Chinese documents

fetchThe function belongs to the global object, we can call it directly, and the
return is an promiseobject

const fetchResponsePromise = fetch(resource [, init])
resource:url routing setting/request object (request is rarely used)
init: optional configuration items

Explanation

resource:This defines the resource you wish to acquire. It can be:
A USVString contains the direct URL of the resource to be obtained. Some browsers accept blob: and data: schemes.
A Request object.

init:The optional configuration item
contains the object of any custom settings to be applied to the request.
method, headers, body, mode, credentials, cache, redirect, referrer, referrerPolicy, integrity, keepalivesignal.

Focus

In the request body:
there can be multiple formats, which can be a Blob, BufferSource, FormData, URLSearchParams, USVString, or ReadableStream object.
Please note that the request GET or HEAD method used cannot have a body.

Case study

1. Create teststwelve文件夹and in this folder
2. Create simpel.html文件
3. Create server.js文件
test chart:
Insert picture description here

simpel.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 style="background-color: tomato;">fetch 发送AJAX请求</button>
    <div id="result" style="width: 180px;height: 100px;border: solid 2px teal;"></div>
    <script>
        // 把所有的按钮标签都选择
        const btns = document.querySelectorAll('button');
        // 第一个按钮
        btns[0].onclick = function(){
     
     
            // fetch请求               如果想要添加url参数可以直接在url里缀加  如[?weixin=888]
            // 1.服务端返回来的是json格式数据    链接
            fetch('http://127.0.0.1:8000/fetchserverjson?weixin=888', {
     
     
            //2.测试服务端返回来是字符串    链接
            // fetch('http://127.0.0.1:8000/fetchserver?weixin=888', {
     
     
                // 请求方法
                method: 'POST',
                // 请求头信息
                headers:{
     
     
                    sex: 'boy',
                    age: 999
                },
                // 请求体
                bady:'发给服务端的字符串',
                // 用then的回调来处理结果
            }).then(response =>{
     
     
                // 1.打印返回的所有对象    console.log(response);
                // console.log(response);
                // 2.把返回来的json对象转化为字符串   需要再添加then,转化之后再打印   return response.text();}).then(response => {console.log(response);
                // return response.text();}).then(response => {console.log(response);
                // 3.如果服务端返回来的是一个json格式数据
                // 3.把返回来的对象转化为json格式  需要再添加then,转化之后再打印     return response.json();}).then(response => {console.log(response);
                return response.json();}).then(response => {
     
     console.log(response);
            })
        }
    </script>
</body>

</html>

server.js文件

// 1. 引入express
const express = require('express');

// 2.创建对象
const app = express();
// 3.创建路由规则  里面的形参 request与response   (自己可以随便定义名字的)
//  建议写成  request与response  因为可以见名思意,方便自己看
// request  对请求报文的封装
// responst 对响应报文的封装
//  请求路径为'/server'

// 当使用post请求时候会因为发送的信息没有收到对应的结果所以回报错
// 所以该处使用all  表示可以接收任意类型的请求      如get post 等等


// 一:fetch的post请求
app.all('/fetchserver', (request, response)=>{
    
    
    response.setHeader('Access-Control-Allow-Origin','*');
    response.setHeader('Access-Control-Allow-Headers','*');
    response.send('get请求成功,服务端返回的是字符串格式.');
});

// 二:axios通用ajax请求 json数据
app.all('/fetchserverjson', (request, response)=>{
    
    
    response.setHeader('Access-Control-Allow-Origin','*');
    response.setHeader('Access-Control-Allow-Headers','*');
    const data = {
    
    
        name: 'fetch函数通用ajax请求的post请求方法,服务端设置了json格式返回'
    };
    let str = JSON.stringify(data);
    setTimeout(()=>{
    
    response.send(str);},200);
});



// 4. 监听端口启动服务
// 这里listen(8000)后面添加了一个回调,用来提示,告诉自己是否监听成功
app.listen(8000, ()=>{
    
    
    console.log("服务已经启动,8000端口监听中......");
});

Guess you like

Origin blog.csdn.net/weixin_47021806/article/details/112211495