后端接口已經(jīng)添加header("Access-Control-Allow-Origin:*");
使用jquery發(fā)送ajax請求正常獲取。
但嘗試使用vue-resource請求時出錯
代碼如下
js
<script src="http://cdnjs.cloudflare.com/ajax/libs/vue/1.0.7/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/vue.resource/1.0.3/vue-resource.min.js"></script>
<p id="app">
<p>{{message}}</p>
<input type="text" v-model="message">
</p>
<script>
Vue.http.options.emulateJSON = true;
new Vue({
el:'#app',
data: {
message:'hello vue.js.'
},
ready: function() {
this.$http.post('http://127.0.0.1/login.php',{name:'admin',password:'123'}, function(data) {
console.log(data);
})
},
});
</script>
login.php
header("Access-Control-Allow-Origin:*");
if($_POST['name']=='admin'&&$_POST['password']=='123')
echo json_encode(array('error'=>200,'msg'=>'登陸成功','userinfo'=>array('username'=>'gdfgdfg')));
else
echo json_encode(array('error'=>505,'msg'=>'登陸失敗'));
結(jié)果
1已攔截跨源請求:同源策略禁止讀取位于 http://127.0.0.1/login.php 的遠程資源。(原因:來自 CORS 預(yù)檢通道的 CORS 頭 'Access-Control-Allow-Headers' 的令牌 'content-type' 無效)。
2火狐響應(yīng)中查看返回null,console.log(data);沒有執(zhí)行
光陰似箭催人老,日月如移越少年。
返回一個Access-Control-Allow-Headers: content-type
的頭
Vue.http.options.emulateJSON = true;
,這就會在請求頭里加上Content-Type: application/json
。這個頭不屬于常規(guī)請求,所以會先發(fā)OPTIONS
的請求確認請求頭是否允許。
解決方法:
headers字段:
http: {
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}
或者使用 vue 方面提供的更加簡單做法:
Vue.http.options.emulateJSON = true;
注意post傳參方式
以上參考了 vue.js 快速入門 一文中寫道的分享[這也得了解下form data和request payload的區(qū)別,才是徹底解決問題之道]; 另外還需注意的是,參數(shù)傳遞方面也跟 get 請求有些區(qū)別, 例如下面使用示例:
if (model === 'POST'){
this.$http.post(apiUrl, params)
.then((response) => {
callback(response.data)
})
.catch(function (response) {
console.log(response)
})
} else {
this.$http.get(apiUrl, {params: params})
.then((response) => {
callback(response.data)
})
.catch(function (response) {
console.log(response)
})
}
參考下來原文:
http://nicejade.github.io/201...