关于vue-resource报错450的解决方案
前端之家收集整理的这篇文章主要介绍了
关于vue-resource报错450的解决方案,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_301_0@本文介绍了关于vue-resource报错450的解决方案,分享给大家,具体如下:
@H_
3010@一、基本使用:
@H301_0@
<div class="jb51code">
<pre class="brush:js;">
import vueResource from 'vue-resource'
Vue.use(vueResource)
@H_
301_0@
2. 调取接口
{
console.log('success',response)
},response => {
console.log('error',response)
})
@H_
301_0@
二、报错450
@H_
301_0@定位
错误信息:请求header没有完全一一对应。Content-Type: application/x-www-form-urlencoded; charset=UTF-8应为Content-Type: application/json; charset=UTF-8,检查
页面代码,发现已经设置了
@H_
301_0@只是
页面没有起作用而已,那究竟是什么原因导致
页面设置的Content-Type失效了呢?继续追溯,发现跟这行
代码有关
代码有关)
@H_
301_0@
三、分析
@H_
301_0@下面分别来讲一下这几行
代码的用处,以及emulateJSON是怎么影响到Content-Type设置的。
@H_
301_0@1. Vue.http.options.crossOrigin
@H_
301_0@这个很明显是设置跨域的,此处不多讲。
@H_
301_0@2. Vue.http.options.emulateHTTP
@H_
301_0@参考地址:
https://github.com/pagekit/vue-resource/blob/develop/src/http/interceptor/method.js
@H_
301_0@摘出源码
export default function (request,next) {
if (request.emulateHTTP && /^(PUT|PATCH|DELETE)$/i.test(request.method)) {
request.headers.set('X-HTTP-Method-Override',request.method);
request.method = 'POST';
}
next();
}
@H_
301_0@大概的意思就是如果请求方式为PUT|PATCH|DELETE,服务器又没法处理这几类请求的时候,设置Vue.http.options.emulateHTTP = true的话可以将X-HTTP-Method-Override设置为PUT|PATCH|DELETE,然后使用普通的post进行请求。
@H_
301_0@关于X-HTTP-Method-Override讲一下,它的使用场景是:
@H_
301_0@在某些HTTP代理
不支持类似PUT|PATCH|DELETE这些类型HTTP请求的情况下,可以通过另一种完全违背协议的HTTP
方法来"代理"。这种协议就是,使客户端发出HTTP POST请求并设置header里X-HTTP-Method-Override值为PUT|PATCH|DELETE。
@H_
301_0@3. Vue.http.options.emulateJSON
@H_
301_0@参考地址:
https://github.com/pagekit/vue-resource/blob/develop/src/http/interceptor/form.js
@H_
301_0@摘出源码
import Url from '../../url/index';
import { isObject,isFormData } from '../../util';
export default function (request,next) {
if (isFormData(request.body)) {
request.headers.delete('Content-Type');
} else if (isObject(request.body) && request.emulateJSON) {
request.body = Url.params(request.body);
request.headers.set('Content-Type','application/x-www-form-urlencoded');
}
next();
}
@H_
301_0@从第17行可以看到,如果设置了emulateJSON的话会默认
加上这句
@H_
301_0@这就是为什么我们设置的Content-Type失效了。只要去掉Vue.http.options.emulateHTTP = true 或者直接置为false就可以了。
@H_
301_0@vue-resource(github)地址:
https://github.com/pagekit/vue-resource
@H_
301_0@以上就是本文的全部
内容,希望对大家的学习有所帮助,也希望大家多多
支持编程之家。