本文介紹了關(guān)于vue-resource報錯450的解決方案,分享給大家,具體如下:
一、基本使用:
1.頁面引入
import vueResource from 'vue-resource' Vue.use(vueResource)
2. 調(diào)取接口
Vue.http.post(url, { 'data1': data1, 'data2': 'data2'}).then(response => { console.log('success', response)}, response => { console.log('error', response)})二、報錯450
定位錯誤信息:請求header沒有完全一一對應(yīng)。Content-Type: application/x-www-form-urlencoded; charset=UTF-8應(yīng)為Content-Type: application/json; charset=UTF-8,檢查頁面代碼,發(fā)現(xiàn)已經(jīng)設(shè)置了
Vue.http.interceptors.push(function (request, next) { request.headers.set('Content-Type', 'application/json; charset=UTF-8') request.headers.set('Content-Type', 'application/json') next()})只是頁面沒有起作用而已,那究竟是什么原因?qū)е马撁嬖O(shè)置的Content-Type失效了呢?繼續(xù)追溯,發(fā)現(xiàn)跟這行代碼有關(guān)
// Vue.http.options.crossOrigin = true // Vue.http.options.emulateHTTP = true Vue.http.options.emulateJSON = true //(跟這行代碼有關(guān))
三、分析
下面分別來講一下這幾行代碼的用處,以及emulateJSON是怎么影響到Content-Type設(shè)置的。
1. Vue.http.options.crossOrigin
這個很明顯是設(shè)置跨域的,此處不多講。
2. Vue.http.options.emulateHTTP
參考地址:https://github.com/pagekit/vue-resource/blob/develop/src/http/interceptor/method.js
摘出源碼
/** * HTTP method override Interceptor. */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();}大概的意思就是如果請求方式為PUT|PATCH|DELETE,服務(wù)器又沒法處理這幾類請求的時候,設(shè)置Vue.http.options.emulateHTTP = true的話可以將X-HTTP-Method-Override設(shè)置為PUT|PATCH|DELETE,然后使用普通的post進(jìn)行請求。
關(guān)于X-HTTP-Method-Override講一下,它的使用場景是:
在某些HTTP代理不支持類似PUT|PATCH|DELETE這些類型HTTP請求的情況下,可以通過另一種完全違背協(xié)議的HTTP方法來"代理"。這種協(xié)議就是,使客戶端發(fā)出HTTP POST請求并設(shè)置header里X-HTTP-Method-Override值為PUT|PATCH|DELETE。
3. Vue.http.options.emulateJSON
參考地址:https://github.com/pagekit/vue-resource/blob/develop/src/http/interceptor/form.js
摘出源碼
/** * Form data Interceptor. */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();}
新聞熱點(diǎn)
疑難解答
圖片精選