• Vue——配置代理(解决ajax跨域问题)



    使用vue脚手架解决ajax跨域请求

    发送ajax请求的4种方式

    • xhr方法: new XMLHttpRequest() (最原始写法) xhr.open() xhr.send()
    • jQuery方法: $get $post
    • axios :(Promise风格)
    • fetch:(Promise风格),fetch的兼容性较差
      jQuery和axios 是对 xhr方法的封装,而fetch方法和xhr方法是平级的,都在window对象身上。

    在Vue中推荐使用axios发送请求。

    使用axios发送ajax请求

    • 安装 :npm i axios
    • 引入:import axios from 'axios'
    • 发送axios请求
          axios.get('http://localhost:5000/students').then(
            response => {
              console.log("响应体内容", response.data)
            },
            error => {
              console.log("请求失败", error.message)
            }
          )
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    跨域问题

    跨域的理解

    同源请求是指协议名、主机名、端口号三者一样
    跨域请求就是是指协议名、主机名、端口号三者有任何一个不一样都是跨域请求。
    而且跨域请求是请求发出去了,浏览器接收并返回了结果,只是浏览器没有接收响应结果。
    在这里插入图片描述

    跨域的报错

    在这里插入图片描述

    跨域的解决

    jsonp 和 CORS

    我们js的跨域解决有两种办法:jsonp 和 CORS

    jsonp 和 CORS的缺点

    • jsonp 靠