標籤: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代理處理跨域的問題