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
  • 相关阅读:
    基于Lumisoft.NET组件开发碰到乱码等一些问题的解决
    Winform开发框架之混合型框架的剖析
    Winform开发框架之通用人员信息管理
    Database2Sharp之混合型Winform框架代码生成
    python3 小技巧(2)
    Python小技巧1
    详解Python模块导入方法
    常见HTTP状态(304,200等)
    python win32api 使用小技巧
    python3下的IE自动化模块PAMIE
  • 原文地址:https://www.cnblogs.com/WattWang/p/vuestudy002.html
Copyright © 2011-2022 走看看