之前 使用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里
最后,問題完美解決!