使用axios以及http-proxy-middleware代理處理跨域的問題

來源:互聯網
上載者:User

標籤:method   本地   gen   roo   proxy   cti   epo   vue-cli   rom   

axios現在以及是尤大大推薦使用的了,官方不在維護vue-reresource.

由於是地第一次使用axios, 在使用過程中猜了很大的坑

首先我們使用vue-cli建立的項目, 提供者肯定是跨域了, 因為我們的本地服務預設的地址一般是localhost:8080 我們的伺服器端肯定不是這個, 所以就形成跨域訪問, axios不支援jsonp, 所以我們就要使用http-proxy-middleware中介軟體做代理,
http-proxy-middleware的github

安裝
npm i axios --save-devnpm install --save-dev http-proxy-middleware// vue-cli 已經把http-proxy-middleware寫在項目依賴裡面了

 

引入axios

在項目的src/main.js引入axios

import axios from ‘axios‘Vue.prototype.$axios = axios;// axios 不支援Vue.use(axios)

 

配置http-proxy-middleware本地代理

開啟config/index.js

var path = require(‘path‘)module.exports = {    build: {        env: require(‘./prod.env‘),        index: path.resolve(__dirname, ‘../dist/index.html‘),        assetsRoot: path.resolve(__dirname, ‘../dist‘),        assetsSubDirectory: ‘static‘,        assetsPublicPath: ‘./‘,        productionSourceMap: false,        // Gzip off by default as many popular static hosts such as        // Surge or Netlify already gzip all static assets for you.        // Before setting to `true`, make sure to:        // npm install --save-dev compression-webpack-plugin        productionGzip: false,        productionGzipExtensions: [‘js‘, ‘css‘],        // Run the build command with an extra argument to        // View the bundle analyzer report after build finishes:        // `npm run build --report`        // Set to `true` or `false` to always turn it on or off        bundleAnalyzerReport: process.env.npm_config_report    },    dev: {        env: require(‘./dev.env‘),        port: 8080,        autoOpenBrowser: true,        assetsSubDirectory: ‘static‘,        assetsPublicPath: ‘/‘,        proxyTable: {            修改這裡修改這裡修改這裡        },        // 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    }}

 

這裡是預設的配置, 找到線面的dev對象裡面的proxyTable修改

proxyTable: {   ‘/api‘: {         target:‘http://www.baidu.com/api‘,         changeOrigin:true,         pathRewrite:{             ‘^/api‘: ‘‘         }     } }

 

target 的參數就是你要訪問的伺服器位址, 你在代碼裡面寫/api就等於寫了這個地址 , 比如我要訪問http://www.baidu.com/api/login這個介面在代碼裡面只需寫/api/login就可以了

至於build/dev.server.js 已經無需修改了, 裡面已經有封裝好了方法了

// proxy api requestsObject.keys(proxyTable).forEach(function (context) {  var options = proxyTable[context]  if (typeof options === ‘string‘) {    options = { target: options }  }  app.use(proxyMiddleware(options.filter || context, options))})

 

網上好多的解決方案都是在build/dev.server.js裡面自己在加內容, 完全不用了

做完上述操作之後一定要重啟服務 ctrl+c然後 npm run dev做完上述操作之後一定要重啟服務 ctrl+c然後 npm run dev做完上述操作之後一定要重啟服務 ctrl+c然後 npm run dev然後我們就可以用axios提供者了
    this.$axios({        method: "POST",        withCredentials: false,        url: "/api/login",        data: {            name: "1511328705UZVQ",            psd: "123456"        }    })    .then(function(res) {         console.log(res);    })    .catch(function(err) {         console.log(err);    });

使用axios以及http-proxy-middleware代理處理跨域的問題

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.