前提使用脚手架安装的情况
第一种本地使用代理的情况
在confin/index.js 13行
proxyTable: {
'/api': {
target: '你自己的接口地址',
changeOrigin:true,//实行跨域
pathRewrite: {
'^/api': ' '
}
}
},
项目的使用 axios本身支持跨域
在src/main.js
import axios from 'axios'
Vue.prototype.$axios = axios
是在你的vue文件内其他请求请看axios的安装和使用教程
var formData = JSON.stringify(this.commons);
console.log(formData)
this.$axios.post('api/commons' ,formData ,{
headers: {'Content-Type':'application/x-www-form-urlencoded'}
})
.then(function (response) {
console.log(response)
if (response.status === 201){
alert('感谢您的来稿,你的建议稍后呈现')
window.location.reload()
}
})
.catch(function (error) {
console.log(error)
});
formDate是你要传递的数据。header头一定要添加。其中用到了axios.
axios的安装和使用教程
https://github.com/axios/axios
打包
npm run build
注意:只是本地可以跑,放在线上的话自行百度如何处理(本人目前没有爬出,服务器是Apache的。有搞定的话请分享下)
第二种不使用代理的情况
请先按第一种的方法进行安装和配置
区别
qs的安装
npm install qs
项目中的使用
在src/main.js
import Qs from 'qs'
Vue.use(Qs)
项目中的文件
const Qs = require('qs')
var formData = Qs.stringify(this.commons);
console.log(formData)
this.$axios.post('你接口数据地址' ,formData ,{
headers: {'Content-Type':'application/x-www-form-urlencoded'}
})
.then(function (response) {
console.log(response)
if (response.status === 201){
alert('感谢您的来稿,你的建议稍后呈现')
window.location.reload()
}
})
.catch(function (error) {
console.log(error)
});
后端的配合(本人后端是PHP用的yii2框架)
public function behaviors()
{
return ArrayHelper::merge([
'contentNegotiator' => [
'class' => ContentNegotiator::className(),
'formats' => [
'text/html' => Response::FORMAT_JSON,
'application/json' => Response::FORMAT_JSON
]
],
[
'class' => Cors::className(),
'cors' => [
'Origin' => ['*'],
'Access-Control-Allow-Methods' => ['POST', 'GET', 'PUT', 'DELETE', 'OPTIONS'],
'Access-Control-Allow-Headers' => ['x-request-with,content-type'],
'Access-Control-Max-Age' => 86400
],
],
],parent::behaviors()); // TODO: Change the autogenerated stub
}
摘要
简明下JSON和qs插件的区别
JSON:{"id":1,"name":tom}
qs id=1&name=tom
第二种方法放到线上
1.打包 npm run build
2.直接配置虚拟主机:域名和指定到你放的项目路径