使用vue-element-admin框架開(kāi)發(fā)時(shí)遇到的跨域問(wèn)題

之前 使用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

https://www.cnblogs.com/zhixi/p/9541162.html

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容