美文网首页Web前端
vue代理解决跨域中的proxyTable、proxy

vue代理解决跨域中的proxyTable、proxy

作者: 李仁平 | 来源:发表于2019-07-29 10:23 被阅读0次

    在vue2x中前端访问api接口时使用代理访问:
    1.proxyTable在vue早期的cli2项目中使用:
    找到文件夹config/index.js,找到代码proxyTable:{},填写需要代理的api,例如api为http://27.154.59.202:8000/module/homePage,代理为
    proxyTable: {
    '/module': {
    target: 'http://27.154.59.202:8000',
    changeOrigin: true,
    // secure: true, //如果是https接口,需要配置这个参数
    pathRewrite: {
    '^/module': '/module'
    }
    },
    }
    index.js文件代码如下:其中var proxyUrl = ''http://27.154.59.202:8000'

    image.png

    我们还需要在文件夹config/dev.env.js做跟改如下:
    'use strict'
    var merge = require('webpack-merge')
    var prodEnv = require('./prod.env')

    module.exports = merge(prodEnv, {
    NODE_ENV: '"development"',
    API_ROOT: '"http://127.0.0.1:8081"', //API地址
    })
    其中API_ROOT本地127.0.0.1::8081为本地端口;
    采用axios插件
    axios.get('${process.env.API_ROOT}/module/homePage', {
    params : { //请求参数

            }
        }).then(function(params) {
            postVue.postCommentByRerocd = params.data.commentByRecordData;
        
        });
    

    2.proxy在vue-cli3项目中使用:
    使用vue-cli3搭建的项目使用跨域代理就简单多了,打开项目找到vue.config.js和package.json同级。
    在vue.config.js中的proxy: {
    '/module': {
    target: '这里填的是后端ip和端口号如:http://27.154.59.202:8000',
    changeOrigin: true,
    // secure: true, //如果是https接口,需要配置这个参数
    pathRewrite: { //把 /module开头的替换成/module
    '^/module': '/module'
    }
    },
    }
    也可以写成这样:
    proxy: {
    '/module': {
    target: '这里填的是后端ip和端口号如:http://27.154.59.202:8000',
    ws: true, //如果要代理 websockets,配置这个参数
    // secure: false, // 如果是https接口,需要配置这个参数
    changeOrigin: true, //是否跨域
    },
    }

    把 /module这里换成你要代理的接口即可。
    精简版的 proxy: '这里填的是后端ip和端口号如:http://27.154.59.202:8000'。


    2020.9.2.png

    如果对你有帮助请点波关注,vue-cli2和vue-cli3的区别请看下一篇文章。

    相关文章

      网友评论

        本文标题:vue代理解决跨域中的proxyTable、proxy

        本文链接:https://www.haomeiwen.com/subject/ppevrctx.html