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;

猜你喜欢

转载自blog.csdn.net/qq_41999617/article/details/84137164