本文介紹了關于vue-resource報錯450的解決方案,分享給大家,具體如下:
一、基本使用:
1.頁面引入
import vueResource from 'vue-resource' Vue.use(vueResource)
2. 調取接口
Vue.http.post(url, { 'data1': data1, 'data2': 'data2' }).then(response => { console.log('success', response) }, response => { console.log('error', response) })
二、報錯450
定位錯誤信息:請求header沒有完全一一對應。Content-Type: application/x-www-form-urlencoded; charset=UTF-8應為Content-Type: application/json; charset=UTF-8,檢查頁面代碼,發現已經設置了
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() })
只是頁面沒有起作用而已,那究竟是什么原因導致頁面設置的Content-Type失效了呢?繼續追溯,發現跟這行代碼有關
// Vue.http.options.crossOrigin = true // Vue.http.options.emulateHTTP = true Vue.http.options.emulateJSON = true //(跟這行代碼有關)
三、分析
下面分別來講一下這幾行代碼的用處,以及emulateJSON是怎么影響到Content-Type設置的。
1. Vue.http.options.crossOrigin
這個很明顯是設置跨域的,此處不多講。
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,服務器又沒法處理這幾類請求的時候,設置Vue.http.options.emulateHTTP = true的話可以將X-HTTP-Method-Override設置為PUT|PATCH|DELETE,然后使用普通的post進行請求。
關于X-HTTP-Method-Override講一下,它的使用場景是:
在某些HTTP代理不支持類似PUT|PATCH|DELETE這些類型HTTP請求的情況下,可以通過另一種完全違背協議的HTTP方法來"代理"。這種協議就是,使客戶端發出HTTP POST請求并設置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(); }
從第17行可以看到,如果設置了emulateJSON的話會默認加上這句
request.headers.set('Content-Type', 'application/x-www-form-urlencoded');
這就是為什么我們設置的Content-Type失效了。只要去掉Vue.http.options.emulateHTTP = true 或者直接置為false就可以了。
vue-resource(github)地址:https://github.com/pagekit/vue-resource
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。