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
  • 相关阅读:
    vscode Nodejs 调试 相关总结
    编程语言中的foo,bar到底是什么
    带T和带Z的相关时间是什么 及关于时间的一些知识
    自定义Firefox的 "切换previous标签页"快捷键, 增加"切回last标签页"快捷键
    开始使用Firefox
    Fork-Join 原理深入分析(二)
    Fork-Join分治编程介绍(一)
    Executor框架(七)Future 接口、FutureTask类
    Executor框架(六)CompletionService 接口
    Executor框架(五)Executors工厂类
  • 原文地址:https://www.cnblogs.com/WattWang/p/vuestudy002.html
Copyright © 2011-2022 走看看