国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

關于vue-resource報錯450的解決方案

2019-11-19 16:00:08
字體:
來源:轉載
供稿:網友

本文介紹了關于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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 三穗县| 津市市| 绥阳县| 蒲江县| 资中县| 炎陵县| 图片| 宁国市| 三穗县| 象山县| 建湖县| 太康县| 新宁县| 灵川县| 阳谷县| 滨州市| 阳原县| 定西市| 阿坝县| 汕尾市| 石台县| 开江县| 修文县| 张家界市| 罗定市| 康保县| 锦州市| 樟树市| 资中县| 黔西县| 昔阳县| 兴国县| 新和县| 滨海县| 育儿| 贞丰县| 漾濞| 广东省| 呈贡县| 鄄城县| 湟源县|