问题描述:
使用 Vue-cli 创建的项目,开发地址是 localhost:8080,需要访问 localhost:8888 上的接口。
分析原因:
不同域名之间的访问,需要跨域才能正确请求。跨域的方法很多,通常都需要后台配置。
不过 Vue-cli 创建的项目,可以直接利用 Node.js 代理服务器,实现跨域请求。
解决方案:
首先axios不支持vue.use()方式声明使用,
建议方式在main.js中如下声明使用
import axios from 'axios';
Vue.prototype.$http=axios;
那么在其他vue组件中就可以this.$http调用使用
1.在我们使用vue-cli构建项目时,会有我们设置跨域请求的文件。
2.在开发过程中,当跨域无法请求的时我们可以修改项目下config文件夹下的index.js中的dev:{}部分
dev: {
env: require('./dev.env'),
port: 8888,
autoOpenBrowser: true,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api':{
target:'http://jsonplaceholder.com',
changeOrigin:true,//允许跨域
pathRewrite:{ //需要rewrite重写的, 如果在服务器端做了处理则可以不要这段
'/api':''
}
}
},
// 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
}
将target设置为我们需要访问的域名。
上面的示例将代理请求/api/posts/1到 ==> http://jsonplaceholder.com/posts/1。
如果 pathRewrite: {
‘^/api’: ‘api’
},
则将代理请求/api/posts/1到 ==> http://jsonplaceholder.com/api/posts/1。
3.然后在main.js中配置全局请求路径:
Vue.prototype.HOST = '/api'
4.至此,我们就可以在全局使用这个域名了,如下:
var url = this.HOST + '/posts/1'
this.$http.get(url).then(res => {
this.dataList = res.data.body;
},res => {
console.info('调用失败');
});
axios发送get post请求问题
发送post请求时一般都要设置Content-Type,
发送内容的类型,application/json指发送json对象但是要提前stringify一下。
application/xxxx-form指发送?a=b&c=d格式,可以用qs的方法格式化一下,
qs在安装axios后会自动安装,只需要组件里import一下即可。
const postData=JSON.stringify(this.formCustomer);
'Content-Type':'application/json'}
const postData=Qs.stringify(this.formCustomer);//过滤成?&=格式
'Content-Type':'application/xxxx-form'}