1、配置config下的index.js
proxyTable: {
'/apis': {
target: 'http://127.0.0.1:3000',
changeOrigin: true,
pathRewrite: {
'^/apis': '/'
}
}
},
2、在main中引入axios
import Vue from 'vue'
import App from './App'
import router from './router'
import axios from 'axios'
import querystring from 'querystring'
const FastClick = require('fastclick')
FastClick.attach(document.body)
Vue.config.productionTip = false
Vue.prototype.$axios = axios
axios.defaults.headers.post['Content-Type']='application/x-www-form-urlencoded';
axios.interceptors.request.use(function (config) {
if(config.method === "post"){
config.data = querystring.stringify(config.data)
}
return config;
},function (error) {
return Promise.reject(error);
});
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
3、在组件中使用
<template>
<div>
1、vue中axios跨域
2、PHP后台验证header头信息
</div>
</template>
<script>
import querystring from 'querystring'
export default {
name: 'jsonp',
created() {
this.$axios({
method: 'POST',
url: '/apis/tencent/jsonp/index.php',
data: {name: "zhangsan", id: '002'},
headers: {'token': '12cDfdjD223'}
}).then((data) => {
console.log(data);
}).catch(function (error) {
console.log(error)
})
//接口地址是127.0.0.1:3000/jsonp/index.php
//通过代理设置apis代表127.0.0.1
//于是接口地址/apis/json/index.php
this.$axios.post('/apis/jsonp/index.php', {
name: 'lisi',
id: '003'
}, {headers: {'token': 'fDDf5541'}})
.then(function (data) {
console.log(data);
}).catch(function (error) {
console.log(error)
})
}
}
</script>
4、PHP后台带接受Header头
注意,在PHP中所有的header中的自定义信息都会被加上HTTP_的开头,在获取的时候参数名称全部会转换成大写
<?php
$name = $_POST['name'];
$id = $_POST['id'];
if(isset($_SERVER['HTTP_TOKEN'])){
$token = $_SERVER['HTTP_TOKEN'];
}else{
$token = '';
}
//后端允许跨域配置
////指定允许其他域名访问
//header("Access-Control-Allow-Origin:*");
//// 响应类型
//header("Access-Control-Allow-Methods:POST,GET,PUT,DELETE,OPTIONS");
//// 响应头设置
//header("Access-Control-Allow-Headers:x-requested-with,content-type");
header("Content-Type:application/x-www-form-urlencoded,charset=utf-8");
if ($token != '') {
$data = array(
'name' => $name,
'id' => $id,
'token'=>$token,
'msg' => "成功"
);
$jsondata = json_encode($data);
echo $jsondata;
} else {
$data = array(
'msg' => '请求不合法'
);
$jsondata = json_encode($data);
echo $jsondata;
}
?>