src/main.js中的配置
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded' //设置请求头部
axios.defaults.baseURL = 'http://127.0.0.1:8081/news/' //所请求的连接
axios.defaults.withCredentials = true //跨域
Vue.prototype.$http = axios
Vue.prototype.$axios = axios
Vue.prototype.$qs = qs
config/index.js的设置
proxyTable: {
'/api' : {
// 测试环境
target: 'http://127.0.0.1:8081/',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
},
在vue中请求
this.$axios
.post('/newType', this.$qs.stringify(this.ruleForm), {headers: {'Content-Type': "application/x-www-form-urlencoded"}})
.then(response => {
withCredentials: true //跨域请求头携带cookie
if(response.data.code == 200){
this.$message({showClose: true, message: '添加成功!', type: 'success'});
return true;
} else{
this.$message({showClose: true, message: '添加失败!', type: 'error'});
return false;
}
})
.catch(error => {
console.log(error)
})
在这次请求中,this.ruleForm是发送的数据,通过this.$qs.stringify将对象序列化,转为ajax的form data 即以&连接的形式,设置头部,否则接收数据发送数据失败,这次请求,实际请求的连接是 127.0.0.1:8081/news/newsType
返回的数据是 response.data
另外,在创建vue时,需要在router/index 中使用import引入,并且要在
{ path: '/', component: TheLayout, menu: true, name: '新闻类别管理', icon: 'el-icon-edit-outline', children: [ { path: '/forms/addtype', name: '新闻类别添加', component: FuncAddType }, { path: '/forms/modtype', name: '新闻类别维护', component: FuncModType }, ] },
写好自己的路由