Vue之前后端交互模式

news/2024/7/10 2:16:07 标签: javascript, vue, axios, fetch

fetchAPI_0">1. fetch-API的使用

1.1 init

<!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>Document</title>
    <!-- 
        0. using Fetch: https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch; 
        1. Fetch API 提供了一个获取资源的接口(包括跨域请求)。
           任何使用过 XMLHttpRequest 的人都能轻松上手,而且新的 API 提供了更强大和灵活的功能集; 
        2. Fetch API 提供了一个 JavaScript 接口,用于访问和操纵 HTTP 管道的一些具体部分,例如请求和响应; 
           它还提供了一```全局 fetch()方法```,该方法提供了一种简单,合理的方式来跨网络异步获取资源; 
     -->

     <!-- 
         fetch(...) => https://developer.mozilla.org/zh-CN/docs/Web/API/fetch
         格式:Promise<Response> fetch(input[, init]);
             1. 参数:
                    (1) input:  定义要获取的资源。这可能是:
                            a. 一个 USVString 字符串,包含要获取资源的 URL; 
                            b. 一个 Request 对象; 
                    (2) init: 一个配置项对象,包括所有对请求的设置。可选的参数有:
                            method:         请求使用的方法,如 GET、POST; 
                            headers:        请求的头信息, ,形式为 Headers 的对象或包含 ByteString 值的对象字面量; 
                            body:           请求的body信息:可能是一个Blob、BufferSource (en-US)、FormData、URLSearchParams 或者 USVString 对象;
                            mode:           请求的模式,如 cors、 no-cors 或者 same-origin; 
                            credentials:    ...
                            cache:          ...
                            redirect:       ...
                            referrer:       ...
                            referrerPolicy: ...
                            integrity:      ...
             2. 返回值:
                    ```它返回一个 promise,这个 promise会在请求响应后被 resolve,并传回Response对象```; 
             3. 与fetch()相关联的对象:
                    (1) Response对象: Fetch API 的 Response 接口呈现了对一次请求的响应数据; 
                    (2) Request对象: Fetch API 的 Request接口用来表示资源请求; 
                    (3) Headers对象: Fetch API 的 Headers 接口允许您对HTTP请求和响应头执行各种操作; 
      -->
</head>
<body>
    
</body>
</html>

1.2 基本使用

<!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>Document</title>
</head>

<body>
    <script>javascript">
        /*
            fetch()函数返回一个 promise,这个 promise会在请求响应后被 resolve,并传回Response对象;
            通过response.text(): 它返回一个包含USVString对象(也就是文本)的Promise对象,返回结果的编码永远是 UTF-8;
        */
        fetch('http://localhost:3000/fdata')    // 返回一个Promise对象
            .then(function (response) {
                return response.text();         // response.text()又是一个Promise对象
            })
            .then(function (text) {
                // console.log(text);
                alert(text); 
            });
    </script>
</body>

</html>

1.3 参数传递

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>

<body>
    <script type="text/javascript">javascript">
        // 1. GET参数传递-传统URL
        /*
            fetch('http://localhost:3000/books?id=123', {
                    method: 'get'
                })
                .then(function (response) {
                    return response.text();
                }).then(function (text) {
                    alert(text); 
                });
        */


        // 2. GET参数传递-restful形式的URL
        /*
            fetch('http://localhost:3000/books/456', {
                    method: 'get'
                })
                .then(function (response) {
                    return response.text();
                }).then(function (text) {
                    alert(text); 
                });
        */


        // DELETE请求方式参数传递
        /*
            fetch('http://localhost:3000/books/789', {
                    method: 'delete'
                })
                .then(function (response) {
                    return response.text();
                }).then(function (text) {
                    alert(text); 
                });
        */


        // POST请求传参(uname=lisi&pwd=123形式)
        /*
            fetch('http://localhost:3000/books', {
                    method: 'post',
                    body: 'uname=lisi&pwd=123',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(function (response) {
                    return response.text();
                }).then(function (text) {
                    alert(text); 
                });
        */

        
        // POST请求传参(json格式)
        /*
            fetch('http://localhost:3000/books', {
                    method: 'post',
                    body: JSON.stringify({
                        uname: '张三',
                        pwd: '456'
                    }),
                    headers: {
                        'Content-Type': 'application/json'
                    }
                })
                .then(function (response) {
                    return response.text();
                })
                .then(function (text) {
                    alert(text);
                });
        */


        // PUT请求传参
            fetch('http://localhost:3000/books/123', {
                    method: 'put',
                    body: JSON.stringify({
                        uname: '张三',
                        pwd: '789'
                    }),
                    headers: {
                        'Content-Type': 'application/json'
                    }
                })
                .then(function (response) {
                    return response.text();
                })
                .then(function (text) {
                    alert(text);
                });
        
    </script>
</body>

</html>

1.4 响应数据格式

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <!-- 
        Fetch响应结果的数据格式
     -->
</head>

<body>
    <script type="text/javascript">javascript">
    /*
        fetch('http://localhost:3000/json').then(function (response) {
                return response.json();
            })
            .then(function (json) {
                console.log(json);
            }); 
    */
        
            fetch('http://localhost:3000/json').then(function (response) {
                return response.text();
            })
            .then(function (jsonText) {
                // console.log(jsonText);              // "{"uname":"lisi","age":13,"gender":"male"}"
                console.log(JSON.parse(jsonText)); 
            }); 
        
    </script>
</body>

</html>

axios_237">2. axios库的基本使用

2.1 init

<!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>Document</title>

    <!-- 
        1. https://www.axios-http.cn/docs/intro
        2. Axios是什么?
            基于promise可以用于浏览器和node.js的网络请求库; 
            Axios 是一个基于promise网络请求库,作用于node.js 和 浏览器中; 
            它是 isomorphic 的(即同一套代码可以运行在浏览器和node.js中); 
            在服务端它使用原生node.js中的http 模块, 而在客户端 (浏览端) 则使用 XMLHttpRequests; 
        2. 具备以下特征:
            a. 从浏览器创建 XMLHttpRequests; 
            b. 从 node.js 创建 http 请求; 
            c. 支持 Promise API; 
            d. 拦截请求和响应; 
            e. 转换请求和响应数据; 
            f. 取消请求; 
            g. 自动转换JSON数据; 
            h. 客户端支持防御XSRF; 
     -->
</head>
<body>

</body>
</html>

2.2 基本使用

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <!-- 
        URLSearchParams对象; 
     -->
</head>

<body>
    <!-- 引入axios网络库 -->
    <script type="text/javascript" src="../js/axios.js"></script>
    <!-- 发起axios网络请求 -->
    <script type="text/javascript">javascript">
        axios.get('http://localhost:3000/adata')
            .then(function (response) {
                console.log(response);
                alert(response.data);
            });
    </script>
</body>

</html>

2.3 参数传递

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>

<body>
    <script type="text/javascript" src="../js/axios.js"></script>
    <script type="text/javascript">javascript">
        /************************************* axios get请求传参 ***********************************/
        // [1.] 传统URL传参
        /*
            axios.get('http://localhost:3000/axios?id=123')
                .then(function (response) {
                    console.log(response.data); 
                }); 
        */

        // [2.] restful风格传参
        /*
            axios.get('http://localhost:3000/axios/123')
                .then(function (response) {
                    console.log(response.data); 
                });
        */

        // [3.] params传参(axios请求配置对象中的一个属性, 必须是一个简单对象 或 URLSearchParams对象)
        /*
            axios.get('http://localhost:3000/axios', {
                    params: {               // 自动被转换成?id=789形式
                        id: 789
                    }
                })
                .then(function (response) {
                    console.log(response.data); 
                });
        */


        /************************************* axios delete请求传参 ***********************************/
        /*
            axios.delete('http://localhost:3000/axios', {
                    params: {
                        id: 111
                    }
                })
                .then(function (response) {
                    console.log(response.data); 
                }); 
        */


        /************************************* axios post请求传参 ***********************************/
        /*
            axios.post('http://localhost:3000/axios', {
                    uname: 'lisi',
                    pwd: 123
                })
                .then(function (response) {
                    console.log(response.data);
                });
            let params = new URLSearchParams();
            params.append('uname', 'zhangsan');
            params.append('pwd', '111');
            axios.post('http://localhost:3000/axios', params)
                .then(function (response) {
                    console.log(response.data); 
                });
        */


        /************************************* axios put请求传参 ***********************************/

        axios.put('http://localhost:3000/axios/123', {
                uname: 'lisi',
                pwd: 123
            })
            .then(function (response) {
                console.log(response.data); 
            });
    </script>
</body>

</html>

2.4 响应结果

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>

<body>

    <script type="text/javascript" src="../js/axios.js"></script>
    <script type="text/javascript">javascript">
    /* 服务器返回json格式数据, 浏览器端的axios将会自动解析json数据格式, response.data就是json对象 */
        axios.get('http://localhost:3000/axios-json')
            .then(function (response) {
                console.log(response.data); 
            }); 
    </script>
</body>

</html>

2.5 全局配置

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>

<body>

    <script type="text/javascript" src="../js/axios.js"></script>
    <script type="text/javascript">javascript">
        // 配置请求的基准URL地址
        axios.defaults.baseURL = 'http://localhost:3000/';
        // 配置请求头信息
        axios.defaults.headers['mytoken'] = 'hello';
        axios.get('axios-json')             // 因为baseURL的存在, 相当于http://localhost:3000/axios-json请求地址
            .then(function (ret) {
                console.log(ret.data.uname)
            });
    </script>
</body>

</html>

2.6 axios拦截器

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>

<body>
    <script type="text/javascript" src="../js/axios.js"></script>
    <script type="text/javascript">javascript">
// 1. 添加请求拦截器
        axios.interceptors.request.use(
            // 在发送请求前做些什么
            function (config) {
                console.log(config);
                config.headers.mytoken = 'nihao';
                return config;
            },
            // 对请求错误做些什么
            function (err) {
                console.log(err)
            });

// 2. 添加响应拦截器
        axios.interceptors.response.use(
            // 对响应数据做点什么
            function (response) {
                return response.data;   // 直接将response.data给返回出去, 此时在then中就可以直接拿到data数据了
            },
            // 对响应错误做点什么
            function (err) {
                console.log(err)
            }); 

        axios
            .get('http://localhost:3000/adata')
            .then(function (data) {
                console.log('***> ' + data); 
            }); 
    </script>
</body>

</html>

在这里插入图片描述

3. index.js

javascript">const express = require('express')
const app = express()
const bodyParser = require('body-parser')
// 处理静态资源
app.use(express.static('public'))
// 处理参数
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// 设置允许跨域访问该服务
app.all('*', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  res.header('Access-Control-Allow-Headers', 'mytoken');
//   res.header('Access-Control-Allow-Headers', '*');
  next();
});
app.get('/async1', (req, res) => {
  res.send('hello1')
})
app.get('/async2', (req, res) => {
  if(req.query.info == 'hello') {
    res.send('world')
  }else{
    res.send('error')
  }
})

app.get('/adata', (req, res) => {
  res.send('Hello axios!')
})
app.get('/axios', (req, res) => {
  res.send('axios get 传递参数' + req.query.id)
})
app.get('/axios/:id', (req, res) => {
  res.send('axios get (Restful) 传递参数' + req.params.id)
})
app.delete('/axios', (req, res) => {
  res.send('axios delete 传递参数' + req.query.id)
})
app.post('/axios', (req, res) => {
  res.send('axios post 传递参数' + req.body.uname + '---' + req.body.pwd)
})
app.put('/axios/:id', (req, res) => {
  res.send('axios put 传递参数' + req.params.id + '---' + req.body.uname + '---' + req.body.pwd)
})

app.get('/axios-json', (req, res) => {
  res.json({
    uname: 'lisi',
    age: 12
  });
})


app.get('/fdata', (req, res) => {
  res.send('Hello Fetch!')
})
app.get('/books', (req, res) => {
  res.send('传统的URL传递参数!' + req.query.id)
})
app.get('/books/:id', (req, res) => {
  res.send('Restful形式的URL传递参数!' + req.params.id)
})
app.delete('/books/:id', (req, res) => {
  res.send('DELETE请求传递参数!' + req.params.id)
})
app.post('/books', (req, res) => {
  res.send('POST请求传递参数!' + req.body.uname + '---' + req.body.pwd)
})
app.put('/books/:id', (req, res) => {
  res.send('PUT请求传递参数!' + req.params.id + '---' + req.body.uname + '---' + req.body.pwd)
})

app.get('/json', (req, res) => {
  res.json({
    uname: 'lisi',
    age: 13,
    gender: 'male'
  });
})

app.get('/a1', (req, res) => {
  setTimeout(function(){
    res.send('Hello TOM!')
  },1000);
})
app.get('/a2', (req, res) => {
  setTimeout(function(){
    res.send('Hello JERRY!')
  },2000);
})
app.get('/a3', (req, res) => {
  setTimeout(function(){
    res.send('Hello SPIKE!')
  },3000);
})

// 路由
app.get('/data', (req, res) => {
  res.send('Hello World!')
})
app.get('/data1', (req, res) => {
  setTimeout(function(){
    res.send('Hello TOM!')
  },1000);
})
app.get('/data2', (req, res) => {
  res.send('Hello JERRY!')
})

// 启动监听
app.listen(3000, () => {
  console.log('running...')
})

http://www.niftyadmin.cn/n/377931.html

相关文章

Java程序设计入门教程-- if 条件语句

目录 单分支选择语句&#xff08;if&#xff09; 双分支选择语句&#xff08;if…else&#xff09; 嵌套if语句 单分支选择语句&#xff08;if&#xff09; 情形 当判断条件满足时&#xff0c;执行语句体S&#xff0c;而不满足则什么都不做。 格式 if &#xff08;条件判断表…

Vue3-devtools开发者工具正确安装方法

目录 前言&#xff1a;1、下载安装2、添加扩展 前言&#xff1a; 最近在学习Vue3&#xff0c;学习Vue3自然离不开调试工具Vue3-Devtools&#xff0c;所以我们需要来下载这个调试工具并放入谷歌浏览器里的扩展程序里面。帮助我们更好的调试vue3里的程序。 1、下载安装 Github下…

《MYSQL必知必会》读书笔记1

目录 行 主键 MYSQL工具 使用MYSQL 连接 检索数据 检索&#xff08;SELECT&#xff09; 限制结果&#xff08;LIMIT&#xff09; 排序检索&#xff08;ORDER BY&#xff09; 过滤数据&#xff08;WHERE&#xff09; 过滤数据&#xff08;AND、OR&#xff09; 通配符…

【C++入门】auto关键字 与 基于范围的for循环(C++11)

目录 引言 类型别名的思考 一、概念 二、使用细则 1.auto与指针和引用结合起来使用 2.在同一行定义多个变量 三、auto不适用的场景 基于范围的for循环&#xff08;C11&#xff09; 一、范围for的语法 二、使用条件 1.for循环迭代的范围必须是确定的 2.迭代的对象要实现…

Flutter问题记录 - TextField组件多行提示文本显示不全

文章目录 前言开发环境问题描述问题分析解决方案最后 前言 梳理Flutter项目的过程中发现还有一些遗留的TODO没处理&#xff0c;其中有一个和TextField组件相关。 开发环境 Flutter: 3.10.1Dart: 3.0.1 问题描述 TextField组件设置maxLines: null不限制行数&#xff0c;同时…

力扣刷题实录(大厂用题)3 —— 912. 排序数组

912. 排序数组 力扣题目地址&#xff1a;https://leetcode.cn/problems/sort-an-array/ 题目描述 给你一个整数数组 nums&#xff0c;请你将该数组升序排列。 示例 1&#xff1a; 输入&#xff1a;nums [5,2,3,1] 输出&#xff1a;[1,2,3,5] 示例 2&#xff1a; 输入&#x…

C++ stack容器介绍

&#x1f914;stack容器介绍&#xff1a; &#x1f4d6; stack是一种数据结构&#xff0c;也可以被称为堆栈。它是一个容器&#xff0c;只允许在最顶层进行插入和删除&#xff0c;并且只能访问最后一个插入的元素。这个元素称为栈顶。所有新插入的元素都被放置在栈顶上面&#…

chatgpt赋能python:Python中的构造函数

Python 中的构造函数 Python 是一门广泛应用于各种应用领域的高级编程语言&#xff0c;它支持不同的编程范式&#xff0c;包括面向对象编程。在面向对象编程中&#xff0c;构造函数是一个重要的概念。本文将介绍 Python 中的构造函数&#xff0c;并介绍如何使用它们来创建对象…