笔记

ajax方式

常用的发送 ajax 方式有哪些?

1. xhr //不常用这种直接操作

xhr 是 new XMLHttpRequest() 的对象。

两个常用的api:

  • xhr.open() 配置请求信息
  • xhr.send() 发出一个请求

在实际工程中,不常 new XHLHttpRequest() ,可能是闲麻烦。
常用的是对 xhr 的 二次封装。E.g jQuery axios

2. jQuery

标准发音:/‘dʒeɪkjuːri/或 /‘dʒeɪkwɪri/

例如:
$.get
$.post

该库核心:封装DOM操作(80%),其它操作(20%)。

3.axios //在用 √

axios 音标:/æksiːəʊs/
特点:
是 jQuery 体积的 1/4

安装 axios

npm i axios

安装过程:

> npm i axios
added 8 packages in 3s
120 packages are looking for funding
  run `npm fund` for details

4.fetch

fetch 和 xhr 属于平级。
在Window就有 fetch方法,可以直接使用。
兼容性差(例如:在IE上无法使用)

跨域

096_配置代理_方式一 - 图1


如上图所示,就属于 跨域问题。

同源策略: 就是三个一致

  1. 协议名
  2. 主机名
  3. 端口号

例如: http://localhost:8080
那么协议名为 http , 主机名为 localhost 端口为 8080

解决跨域的三种方法:

  1. CROS
    CROS解决跨域,才是真正意义上的跨域。
    因为 浏览器 如果通过 CROS请求 服务器,那么服务器在响应回传数据的时候,添加了特殊的响应头,浏览器一看见这些响应头就知道:虽然你跨域了,但是服务器已经表态了,这个数据要给你,那么浏览器就会一抬手把数据给你了。

  2. jsonp
    jsonp 是一种巧妙地借助 script标签中的src属性在引入外部资源的时候,不受同源策略限制的这一特点办到的。
    这种方式,需要前端和后端人员一起努力才行。
    这种方式,只能解决get问题,不能解决post问题,所以比较鸡肋。

  3. 配置一个代理服务器
    为了方便操作,我们用 Vue CLI 脚手架配置一个代理服务器。
    这种方法,只能配置一个代理,不能配置多个。

根据教程,我没有找到对应的 test_proxy_server.zip 压缩包,所以我根据视频内容模拟了相关的数据,大家可以直接访问:

重要源码

App.vue

<template>
    <div>
        <button @click="getStudents">获取学生信息</button>
    </div>
</template>

<script>
    //引入 axios
    import axios from 'axios'

    export default {
        name:'App',

        methods:{
            getStudents(){
                //axios.get('https://asciim.cn/m/json/000_test_proxy_server/students/').then( //给2个回调:成功回调+失败回调
                //通过 代理服务器 拿数据:
                axios.get('http://localhost:8080/m/json/000_test_proxy_server/students/').then( //给2个回调:成功回调+失败回调
                    response => { //如果成功了,就输出
                        console.log('请求成功了',response.data)
                    },
                    error => {
                        console.log('请求失败了',error.message)
                    }
                )
            }
        }
    }
</script>

vue.config.js

//如何使用,参考官网 https://cli.vuejs.org/zh/config/ 
//该文件最终输送给 webpack(基于 Node.js, 而Node.js采用的是 CommonJS) 

const { defineConfig } = require('@vue/cli-service')
//暴露方式: CommonJS
module.exports = defineConfig({
  transpileDependencies: true,

  pages:{
    index:{
      //入口
      entry:'src/main.js',
    },
  },
  lintOnSave:false, //关闭语法检查

  //开启代理服务器
  devServer:{
    //proxy: 'http://localhost:5000'
    //注意:只能配置一个代理
    proxy: 'https://asciim.cn/'
  }
})

vue.config.js

//如何使用,参考官网 https://cli.vuejs.org/zh/config/ 
//该文件最终输送给 webpack(基于 Node.js, 而Node.js采用的是 CommonJS) 

const { defineConfig } = require('@vue/cli-service')
//暴露方式: CommonJS
module.exports = defineConfig({
  transpileDependencies: true,

  pages:{
    index:{
      //入口
      entry:'src/main.js',
    },
  },
  lintOnSave:false, //关闭语法检查

  //开启代理服务器
  devServer:{
    //proxy: 'http://localhost:5000'
    //注意:只能配置一个代理
    proxy: 'https://asciim.cn/'
  }
})