之前 使用js和jquery開(kāi)發(fā)時(shí)也碰到過(guò)接口請(qǐng)求時(shí)的跨域問(wèn)題,
但是在使用vue-element-admin開(kāi)發(fā)也碰到這個(gè)問(wèn)題,而且不能使用之前的方法解決,查過(guò)不少資料,找到一個(gè)很好的方法解決了這個(gè)問(wèn)題
首先,解決的思路是:
1,原因,
造成跨域的原因是因?yàn)槲覀冊(cè)O(shè)置的接口和請(qǐng)求的接口不同造成,而且一般做前后端 分享,后端 接口和前端文件不在同一個(gè)工程,也是造成跨域的原因
2,解決思路
在以前js和jquery時(shí)候,都是設(shè)置josnp或是后端 修改數(shù)據(jù)接口類(lèi)型,解決起來(lái)非常麻煩
在使用vue后,只要使用代理接口就可以解決
3,開(kāi)發(fā)環(huán)境所用工具
a,webpack
b,vue
c,vue-element-admin
d,php
e,http-proxy-middleware[解決跨域的webpack插件]
4,解決步驟
一,安裝 http-proxy-middleware 插件
$ npm install --save-dev http-proxy-middleware</pre>
二,配置dev.evn.js文件

image
三,配置api/index.js文件

image
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: { '/api': { //這里是公共部分,在調(diào)用接口時(shí)后面接不相同的部分,/api就相當(dāng)于http://192.168.0.199:8926/api這一段
target: 'http://ohmgood.com/', //這里寫(xiě)的是訪問(wèn)接口的域名和端口號(hào)
changeOrigin: true, // 必須加上這個(gè)才能跨域請(qǐng)求
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 },
四,配置調(diào)用接口文件【例如login.js

image
ps,記得把框架里的示例接口數(shù)據(jù)關(guān)掉,否則接口地址會(huì)直接請(qǐng)求本地的例子數(shù)據(jù),該關(guān)口在views/main.js里

image
最后,問(wèn)題完美解決!

image