zoukankan      html  css  js  c++  java
  • Vue学习笔记(二):使用Axios进行跨域请求

    简述

    环境: Vue-CLI@4

    假设接口的地址为 http://localhost:5000/api/ctrip/plan?deaprtureTime=2020-10-02&dcity=上海&acity=乌鲁木齐
    前端地址为 http://localhost:8080


    在vue.config.js中设置proxy,vue.config.js和package.json同级,若没有则自己新建。 在以下的例子中,/spider,作为请求接口的前缀,以及匹配使用的proxy,将axios的bashUrl设置为/spider,然后通过pathRewrite把这个重写掉,因为我们实际的请求中并没有这个。在下面的例子里,axios请求的地址为 /spider/api/ctrip/plan?deaprtureTime=2020-10-02&dcity=上海&acity=乌鲁木齐,通过proxy请求的 http://localhost:8080/spider/api/ctrip/plan?deaprtureTime=2020-10-02&dcity=上海&acity=乌鲁木齐,这个在浏览器的开发者工具里看到的也是这个。然后实际去请求数据的地址是 http://localhost:5000/api/ctrip/plan?deaprtureTime=2020-10-02&dcity=上海&acity=乌鲁木齐


    假设使用"/api",作为前缀,而且axios请求接口的地址也以/api开头,则可以不用pathRewrite。

    axios 使用

    import axios from 'axios'
    
    const testapi = {};
    
    testapi.getFlights = function () {
        var result= {};
        axios.defaults.baseURL = '/spider'
    
        axios.get('/api/ctrip/plan?deaprtureTime=2020-10-02&dcity=上海&acity=乌鲁木齐')
        .then(response => result = response.data)
        .catch(function (err) {
            console.error(err)
        });
        return result
    }
    
    export default testapi

    在vue.config.js中配置proxy(代理)

    module.exports = {
        devServer: {
            proxy: {
                '/spider': {
                    target: 'http://localhost:5000',    // 接口的地址
                    changeOrigin: true,    // 允许改变源
                    pathRewrite: {
                        '^/spider': '/'    // 实际的接口地址没有这个,重写掉
                    }
                }
            }
        }
    }

    实际使用

    注意事项

    • 每次修改完之后要重新编译一遍然后重新启动去请求才有效,不然可能没有改动。  
    • 对于不同的开发和生产环境,只需将vue.config.js中的target的地址替换掉就可以了。
    • 参考资料:https://blog.csdn.net/jikangjian/article/details/80798677
  • 相关阅读:
    分布式发布订阅消息系统 Kafka 架构设计[转]
    KAFKA分布式消息系统[转]
    文本协议与二进制协议的选择
    实现程序的热升级
    实现程序的热升级
    一个Socket数据处理模型
    关于GC进行垃圾回收的时机
    多线程
    线程同步(AutoResetEvent与ManualResetEvent)
    异步
  • 原文地址:https://www.cnblogs.com/WattWang/p/vuestudy002.html
Copyright © 2011-2022 走看看