axios如今以及是尤大大推荐使用的了,官方不在维护vue-reresource.css
因为是地第一次使用axios, 在使用过程当中猜了很大的坑html
首先咱们使用vue-cli建立的项目, 访问接口确定是跨域了, 由于咱们的本地服务默认的地址通常是localhost:8080 咱们的服务器端确定不是这个, 因此就造成跨域访问, axios不支持jsonp, 因此咱们就要使用http-proxy-middleware中间件作代理,
http-proxy-middleware的githubvue
npm i axios --save-dev npm install --save-dev http-proxy-middleware // vue-cli 已经把http-proxy-middleware写在项目依赖里面了
在项目的src/main.js
引入axioswebpack
import axios from 'axios' Vue.prototype.$axios = axios; // axios 不支持Vue.use(axios)
打开config/index.js
ios
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修改git
proxyTable: { '/api': { target:'http://www.baidu.com/api', changeOrigin:true, pathRewrite:{ '^/api': '' } } }
target
的参数就是你要访问的服务器地址, 你在代码里面写/api
就等于写了这个地址 , 好比我要访问http://www.baidu.com/api/login
这个接口在代码里面只需写/api/login
就能够了github
至于build/dev.server.js
已经无需修改了, 里面已经有封装好了方法了web
// proxy api requests Object.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
里面本身在加内容, 彻底不用了vue-cli
ctrl+c
而后npm run dev
ctrl+c
而后npm run dev
ctrl+c
而后npm run dev
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); });