1. 程式人生 > >vue-resource 跨域 post請求詳解

vue-resource 跨域 post請求詳解

vue-resource 跨域 post請求時,需要後端工程師配合設定 Access-Control-Allow-Origin 為 *

在使用之前要下載和引入:
cnpm install vue-resource --save  //這裡我使用的是淘寶的cnpm,沒有下載的可使用npm下載cnpm

下載後,在main.js中:

import  VueResource  from 'vue-resource'

Vue.use(VueResource) 

前端請求:

this.$http.post("http://localhost:8080/user/login",{username:"gaogaogao",password:"123456"},{emulateJSON: false})
            .then(
              (response)=>{
                console.log(response); 
              },
              (error)=>{
                console.log(error);
              }
            );

一定要設定 {emulateJSON: true},不然跨域不成功. 
如果Web伺服器無法處理編碼為application/json的請求,你可以啟用emulateJSON選項。啟用該選項後,請求會以application/x-www-form-urlencoded作為MIME type,就像普通的HTML表單一樣

 詳細解釋:

emulateJSON(布林值)
預設值為:false,當值為true並且data為物件時,設定請求頭Content-Type的值為application/x-www-form-urlencoded

如果伺服器無法處理編碼為application/json的請求,可以啟用emulateJSON選項。啟用之後,請求會以application/x-www-form-urlencoded為MIME type,就像普通的HTML表單一樣。

this.$http.post中的第三個引數可寫成全域性(main.js)的:

Vue.http.options.emulateJSON = false;