使用vue-element-admin框架开发时遇到的跨域问题

之前 使用js和jquery开发时也碰到过接口请求时的跨域问题,

但是在使用vue-element-admin开发也碰到这个问题,而且不能使用之前的方法解决,查过不少资料,找到一个很好的方法解决了这个问题

首先,解决的思路是:

1,原因,

造成跨域的原因是因为我们设置的接口和请求的接口不同造成,而且一般做前后端 分享,后端 接口和前端文件不在同一个工程,也是造成跨域的原因

2,解决思路

在以前js和jquery时候,都是设置josnp或是后端 修改数据接口类型,解决起来非常麻烦

在使用vue后,只要使用代理接口就可以解决

3,开发环境所用工具

a,webpack

b,vue

c,vue-element-admin

d,php

e,http-proxy-middleware[解决跨域的webpack插件]

4,解决步骤

一,安装 http-proxy-middleware 插件

1 $ npm install --save-dev http-proxy-middleware

二,配置dev.evn.js文件

 

三,配置api/index.js文件

 

  dev: {
    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/api': {     //这里是公共部分,在调用接口时后面接不相同的部分,/api就相当于http://192.168.0.199:8926/api这一段
        target: 'http://ohmgood.com/',   //这里写的是访问接口的域名和端口号
        changeOrigin: true, // 必须加上这个才能跨域请求
        pathRewrite: {  // 重命名
          '^/apis': ''
        }
      }
    },
    // Various Dev Server settings

    // can be overwritten by process.env.HOST
    // if you want dev by ip, please set host: '0.0.0.0'
    host: 'localhost',
    port: 9527, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
    autoOpenBrowser: true,
    errorOverlay: true,
    notifyOnErrors: false,
    poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-

    // Use Eslint Loader?
    // If true, your code will be linted during bundling and
    // linting errors and warnings will be shown in the console.
    useEslint: true,
    // If true, eslint errors and warnings will also be shown in the error overlay
    // in the browser.
    showEslintErrorsInOverlay: false,

    /**
     * Source Maps
     */

    // https://webpack.js.org/configuration/devtool/#development
    devtool: 'cheap-source-map',

    // CSS Sourcemaps off by default because relative paths are "buggy"
    // with this option, according to the CSS-Loader README
    // (https://github.com/webpack/css-loader#sourcemaps)
    // In our experience, they generally work as expected,
    // just be aware of this issue when enabling this option.
    cssSourceMap: false
  },

 

四,配置调用接口文件【例如login.js

 

ps,记得把框架里的示例接口数据关掉,否则接口地址会直接请求本地的例子数据,该关口在views/main.js里

 

 

 

最后,问题完美解决!

posted @ 2018-08-27 11:24  知兮  阅读(40393)  评论(4编辑  收藏  举报