最近在學習Vue+element搭建一個后台管理項目。在實現跨域開發時踩過的那些坑。
1、開發環境下,如何做好跨域配置
首先跨域我們要配置的文件有:config下的index.js
dev: {
proxyTable: {
'/api': {
target: 'http://10.1.5.11:8080/',//設置你調用的接口域名和端口號
changeOrigin: true, //跨域
pathRewrite: {
'^/api': '/' //這里理解成用‘/api’代替target里面的地址,
后面組件中我們掉接口時直接用api代替
比如我要調用'http://10.1.5.11:8080/xxx/duty?time=2017-07-07 14:57:22',
直接寫‘/api/xxx/duty?time=2017-07-07 14:57:22’即可
在開發環境顯示地址:http://localhost:9600//api/xxx/duty?time=2017-07-07 14:57:22
} }
config/dev.env.js:
module.exports = merge(prodEnv, {
NODE_ENV: '"development"',//開發環境
API_HOST:"/api/"
})
跨域成功,但是這只是開發環境(dev)中解決了跨域問題,生產環境中真正部署到服務器上如果是非同源還是存在跨域問題,
如我們部署的服務器端口是3001,需要前后端聯調,第一步前端我們可以分生產production和開發development兩種環境分別測試,
在config/dev.env.js和prod.env.js里也就是開發/生產環境下分別配置一下請求的地址API_HOST,開發環境中我們用上面配置的代理地址api,
生產環境下用正常的接口地址,所以這樣配置,分別在config/dev.env.js和prod.env.js兩個文件中進行以下配置。
生產環境配置:prod.env.js
module.exports = {
NODE_ENV: '"production"',//生產環境
API_HOST:'"http://10.1.5.11:8080/"'
}
當然不管是開發還是生產環境都可以直接請求http://10.1.5.11:8080//。配置好之后測試時程序會自動判斷當前是開發還是生產環境,然后自動匹配API_HOST,
我們在任何組件里都能用process.env.API_HOST來使用地址如:
instance.post(process.env.API_HOST+'user/login', this.form)
1
然后第二步后端服務器配置一下cros跨域即可,就是access-control-allow-origin:*允許所有訪問的意思。
1
然后第二步后端服務器配置一下cros跨域即可,就是access-control-allow-origin:*允許所有訪問的意思。
綜上:開發的環境下我們前端可以自己配置個proxy代理就能跨域了,真正的生產環境下還需要后端的配合的。
某大神說:此方法ie9及以下不好使,如果需要兼容,最好的辦法是后端在服務器端口加個代理,效果類似開發時webpack的代理。
axios發送get post請求問題
發送post請求時一般都要設置Content-Type,發送內容的類型,application/json指發送json對象但是要提前JSON.stringify()一下。application/xxxx-form指發送?
a=b&c=d格式,可以用qs.stringify()的方法格式化一下,qs在安裝axios后會自動安裝,只需要組件里import一下即可。
const postData=JSON.stringify(this.formCustomer);
'Content-Type':'application/json'}
const postData=Qs.stringify(this.formCustomer);//過濾成?&=格式
'Content-Type':'application/xxxx-form'}
1
2
3
4
5
攔截器的使用
當我們訪問某個地址頁面時,有時會要求我們重新登錄后再訪問該頁面,也就是身份認證失效了,如token丟失了,或者是token依然存在本地,但是卻失效了,所以單單判斷本地有沒有token值不能解決問題。此時請求時服務器返回的是401錯誤,授權出錯,也就是沒有權利訪問該頁面。 我們可以在發送所有請求之前和操作服務器響應數據之前對這種情況過濾。
// http request 請求攔截器,有token值則配置上token值
axios.interceptors.request.use(
config => {
if (token) { // 每次發送請求之前判斷是否存在token,如果存在,則統一在http請求的header都加上token,不用每次請求都手動添加了
config.headers.Authorization = token;
}
return config;
},
err => {
return Promise.reject(err);
});
// http response 服務器響應攔截器,這里攔截401錯誤,並重新跳入登頁重新獲取token
axios.interceptors.response.use(
response => {
return response;
},
error => {
if (error.response) {
switch (error.response.status) {
case 401:
// 這里寫清除token的代碼
router.replace({
path: 'login',
query: {redirect: router.currentRoute.fullPath} //登錄成功后跳入瀏覽的當前頁面
})
}
}
return Promise.reject(error.response.data)
});
至此跨域設置成功,不過雖然設置成功了,不過還有幾個坑是大家比較沒有注意的,就是關於Post的時候如果沒有傳遞參數,會有Options報錯,
這個可能是Vue里面的一個問題,反正我的都有參數傳遞,所以這個問題基本不大。
不過如果出現類似http status 400 ,401 ,405等情況,這個不是跨域設置不成功,很可能是你傳遞的參數或者Http里面的一些格式的問題。
下圖是本人在Vue中踩過的一個坑:
發送post請求時一般都要設置Content-Type,發送內容的類型,application/json指發送json對象但是要提前JSON.stringify()一下。application/xxxx-form指發送?
a=b&c=d格式,可以用qs.stringify()的方法格式化一下,qs在安裝axios后會自動安裝,只需要組件里import一下即可。
const postData=JSON.stringify(this.formCustomer);
'Content-Type':'application/json'}
const postData=Qs.stringify(this.formCustomer);//過濾成?&=格式
'Content-Type':'application/xxxx-form'}
1
2
3
4
5
攔截器的使用
當我們訪問某個地址頁面時,有時會要求我們重新登錄后再訪問該頁面,也就是身份認證失效了,如token丟失了,或者是token依然存在本地,但是卻失效了,所以單單判斷本地有沒有token值不能解決問題。此時請求時服務器返回的是401錯誤,授權出錯,也就是沒有權利訪問該頁面。 我們可以在發送所有請求之前和操作服務器響應數據之前對這種情況過濾。
// http request 請求攔截器,有token值則配置上token值
axios.interceptors.request.use(
config => {
if (token) { // 每次發送請求之前判斷是否存在token,如果存在,則統一在http請求的header都加上token,不用每次請求都手動添加了
config.headers.Authorization = token;
}
return config;
},
err => {
return Promise.reject(err);
});
// http response 服務器響應攔截器,這里攔截401錯誤,並重新跳入登頁重新獲取token
axios.interceptors.response.use(
response => {
return response;
},
error => {
if (error.response) {
switch (error.response.status) {
case 401:
// 這里寫清除token的代碼
router.replace({
path: 'login',
query: {redirect: router.currentRoute.fullPath} //登錄成功后跳入瀏覽的當前頁面
})
}
}
return Promise.reject(error.response.data)
});
至此跨域設置成功,不過雖然設置成功了,不過還有幾個坑是大家比較沒有注意的,就是關於Post的時候如果沒有傳遞參數,會有Options報錯,
這個可能是Vue里面的一個問題,反正我的都有參數傳遞,所以這個問題基本不大。
不過如果出現類似http status 400 ,401 ,405等情況,這個不是跨域設置不成功,很可能是你傳遞的參數或者Http里面的一些格式的問題。
下圖是本人在Vue中踩過的一個坑:
這個是由於傳遞的HTTP參數格式有問題,本人查找了好久終於發現問題所在,原來是接口要求傳遞的參數封裝body,由於初次接觸,本人使用了params傳遞,造成requestbody為null。在傳遞參數是使用config.data即可成功傳輸。具體的請求報錯信息本人從這里找到,最后終於解決掉:{"timestamp":1523978119930,"status":400,"error":"Bad Request","exception":"org.springframework.http.converter.HttpMessageNotReadableException","message":"Required request body is missing:
參考具體的Http狀態解決問題:
http含義:
http含義:
http 200:-文件被正常的訪問
http 302:臨時重定向
HTTP錯誤列表
HTTP 400 - 請求無效
HTTP 401.1 - 未授權:登錄失敗
HTTP 401.2 - 未授權:服務器配置問題導致登錄失敗
HTTP 401.3 - ACL 禁止訪問資源
HTTP 401.4 - 未授權:授權被篩選器拒絕
HTTP 401.5 - 未授權:ISAPI 或 CGI 授權失敗
HTTP 403 - 禁止訪問
HTTP 403 - 對 Internet 服務管理器 (HTML) 的訪問僅限於 Localhost
HTTP 403.1 禁止訪問:禁止可執行訪問
HTTP 403.2 - 禁止訪問:禁止讀訪問
HTTP 403.3 - 禁止訪問:禁止寫訪問
HTTP 403.4 - 禁止訪問:要求 SSL
HTTP 403.5 - 禁止訪問:要求 SSL 128
HTTP 403.6 - 禁止訪問:IP 地址被拒絕
HTTP 403.7 - 禁止訪問:要求客戶證書
HTTP 403.8 - 禁止訪問:禁止站點訪問
HTTP 403.9 - 禁止訪問:連接的用戶過多
HTTP 403.10 - 禁止訪問:配置無效
HTTP 403.11 - 禁止訪問:密碼更改
HTTP 403.12 - 禁止訪問:映射器拒絕訪問
HTTP 403.13 - 禁止訪問:客戶證書已被吊銷
HTTP 403.15 - 禁止訪問:客戶訪問許可過多
HTTP 403.16 - 禁止訪問:客戶證書不可信或者無效
HTTP 403.17 - 禁止訪問:客戶證書已經到期或者尚未生效
HTTP 404.1 - 無法找到 Web 站點
HTTP 404 - 無法找到文件
HTTP 405 - 資源被禁止
HTTP 406 - 無法接受
HTTP 407 - 要求代理身份驗證
HTTP 410 - 永遠不可用
HTTP 412 - 先決條件失敗
HTTP 414 - 請求 - URI 太長
HTTP 500 - 內部服務器錯誤
HTTP 500.100 - 內部服務器錯誤 - ASP 錯誤
HTTP 500-11 服務器關閉
HTTP 500-12 應用程序重新啟動
HTTP 500-13 - 服務器太忙
HTTP 500-14 - 應用程序無效
HTTP 500-15 - 不允許請求 global.asa
Error 501 - 未實現
HTTP 502 - 網關錯誤
錯誤碼與狀態碼
近來總有朋友咨詢cPanel的Awstats中“HTTP錯誤碼(HTTP Error codes)”的含義,以及是否需要關注和處理。
關於Awstats請查看《CP How-To:如何使用cPanel查看站點統計數據(awstats)》
文章地址:
http://bbs.netpu.net/viewthread.php?tid=694
其實這是一個誤會,在這里它應該是“HTTP狀態碼(HTTP Status codes)”。
OK,既然是狀態碼,那么就可能有正確和錯誤兩種狀態了(至少不全是錯誤了,大大的松口氣吧)。那么這些代碼都代表什么含義呢?到底哪些是錯誤狀態,哪些是正確狀態呢?不要急,下邊我冒充內行為大家做一個簡單的介紹。
HTTP與Status codes
HTTP可能大家都熟悉,就是超文本傳輸協議。瀏覽器通過HTTP與WEB Server通訊(也有一些其它軟件比如IM使用HTTP協議傳遞數據),把我們的請求(HTTP Request)傳遞給服務器,服務器響應這個請求,返回應答(HTTP Response)以及我們需要的數據。大致就是這個樣子了。
如果我們請求啥,服務器就返回啥,是乎就不需要HTTP Status codes了。但是事情往往不是那么簡單。比如我們請求一個網頁頁面,可是服務器不存在這個頁面,或者這個頁面被轉移到其它地方,或者服務器禁止我們查看這個頁面等等,所以為了便於瀏覽器處理這些正確與不正確的情況,HTTP用Status codes來表示請求(HTTP Request)在服務器端被處理的情況。Status codes通過應答(HTTP Response)返回給瀏覽器,瀏覽器根據這個作相應的處理。
HTTP Status codes的分類
既然有正確和錯誤的狀態,HTTP定義兩大類狀態碼是不是就可以了?人家制訂協議的可是專家(不象我是冒充的),想得比我們要周全,要長遠。HTTP 1.1中定義了5大類Status codes,分別是:
Informational
意義:信息
范圍:1XX
Successful
意義:成功
范圍:2XX
Redirection
意義:重定向
范圍:3XX
Client Error
意義:客戶端錯誤
范圍:4XX
Server Error
意義:服務器錯誤
范圍:5XX
您看看人家想得多周到啊,真專家就是真專家。
常見HTTP Status codes簡介
下面簡單介紹一下我們經常碰到的HTTP Status codes。
也許是我孤陋寡聞,常遇到的HTTP Status codes就那么幾個,見笑啦。
Successful
200 - OK:OK
這個是最常見的啦(也許我們不會直接看到,但是如果您使用一些抓包工具,大多數http應答中都有這個)。意義很簡單,就是說服務器收到並理解客戶端的請求而且正常處理了。
206 - Partial Content:部分內容。
這個也經常發生。很容易讓大家發懵。
通俗點說就是如果客戶端請求文檔(圖像,文本,聲音等等)的部分內容,服務器正常處理,那么就返回206。大致意思就是它請求的時候,除了指定請求的內容,還指定了偏移量以及長度。
部分內容,沒搞錯吧?呵呵沒搞錯,現在很多瀏覽器以及軟件支持斷點續傳就是靠這個的。呵呵,以后看到206不要怕了。
Redirection
301 - Moved Permanently:永久移動。
這個狀態碼是指客戶端要請求的資源已經被永久的轉移到一個新的地方了。這個應答(HTTP Response)里邊同時包含了資源的新地址。它告訴客戶端,如果下次還想要這個資源,那么就用新的地址去取。
302 Found:臨時重定向。
這個狀態碼是指客戶端要請求的資源臨時放到一個新地方了。同樣,應答中也包含了資源的新地址。
307 - Temporary Redirect:臨時重定向。(如果不去實現協議或者做相關開發,我們大致理解它很302差不多就可以啦)
Client Error
400 - Bad Request:錯誤請求
就是請求的語法錯誤,服務器無法理解。
401 – Unauthorized:未授權
當服務器返回401 Code,就是告訴說客戶端訪問指定資源以前,必須通過服務器的授權。
403 – Forbidden:禁止訪問
就是不允許訪問某些資源。
404 - Not Found:找不到
找不到客戶端請求的內容
Server Error
500 - Internal Server Error
服務器內部錯誤。
結束語
越寫越懶,所以就簡簡單單寫這么多啦。沒有啥大用處。如果能消除一兩位關於這方面朋友的疑慮,就足以令我欣慰了。既然之前都說過是冒充內行,所以有錯漏之處在所難免,還望大家不吝賜教。
需要深入研究這方面內容的朋友,千萬不要看這篇文章,以免被此文誤導。請學習官方的協議內容。
官方的資料地址:
源文檔 <http://www.51testing.com/?134114/action_viewspace_itemid_99305.html>
http error codes
400 invalid syntax. 語法問題
401 access denied. 訪問拒絕
402 payment required. 必須完整
403 request forbidden. 請求被禁止
404 object not found. 對象沒有找到
405 method is not allowed. 方法不允許
406 no resp acceptable to client found. 客戶端沒有響應
407 proxy authentication required. 代理需要驗證
408 server timed out waiting for request. 等等請求時服務器斷開連接
409 user should resubmit with more info. 有沖突用戶應該進行檢查
410 resource is no l available. 資源不可用
411 server refused to accept request without a length. 服務器拒絕接受沒有長度的請求
412 prec given in request failed. 放棄請求失敗的條件
413 request entity was too large. 請求太大
414 request uniform resource identifier (uri) too long. 請求的uri 太長
415 unsupported media type. 不支持media類型
449 retry after doing the appropriate action. 在作了適當動作后重試
500 internal server error. 服務器內部錯誤
501 server does not support the functi required to fulfill the request. 服務器不支持請求的功能
502 error resp received from gateway. 從網關收到錯誤應答
503 temporarily overloaded. 過載
504 timed out waiting for gateway. 等待網關時請求斷開
505 http version not supported. 不支持http的版本
http status codes returned by servers on the internet.
從internet返回的http status代碼(http 狀態字)
http_status_continue (100)
the request can be continued.
請求不能被繼續
http_status_switch_protocols (101)
the server has switched protocols in an upgrade header.
通過新的header服務器的協議被轉換了
http_status_ok (200)
the request completed successfully.
請求成功的完成
http_status_created (201)
the request has been fulfilled and resulted in the creation of a new resource.
通過新的資源請求已經被完成
http_status_accepted (202)
the request has been accepted for processing, but the processing has not been completed.
請求已經被接受處理,但是處理還沒有完成
http_status_partial (203)
the returned meta information in the entity-header is not the definitive set available from the origin server.
從服務器返回的在entity-header中的meta信息是無效的
http_status_no_content (204)
the server has fulfilled the request, but there is no new information to send back.
服務器實現了請求,但是沒有返回信息
http_status_reset_content (205)
the request has been completed, and the client program should reset the document view that caused the request to be sent to allow the user to easily initiate another input action.
請求已經被完成,並且web程序(客戶端程序瀏覽器程序)已經重置了文檔視圖目錄(c
http_status_partial_content (206)
the server has fulfilled the partial get request for the resource.
服務器已經為資源完成了部分get請求
http_status_ambiguous (300)
the server couldn't decide what to return.
服務器不能判定返回什么
http_status_moved (301)
the requested resource has been assigned to a new permanent uri (uniform resource identifier), and any future references to this resource should be d using of the returned uris.
被請求的資源已經被分配給新的uri,並且以后引用時都使用這個uris資源。
http_status_redirect (302)
the requested resource resides temporarily under a different uri (uniform resource identifier).
請求的資源臨時在不同的uri下
http_status_redirect_method (303)
the resp to the request can be found under a different uri (uniform resource identifier) and should be retrieved using a get http verb on that resource.
請求的資源不能在不同的uri下找到,並且從新使用get http在服務器上從新檢索
http_status_not_modified (304)
the requested resource has not been modified.
請求的資源沒有被改變
http_status_use_proxy (305)
the requested resource must be accessed through the proxy given by the location field.
請求的資源必須通過特定的代理獲得
http_status_redirect_keep_verb (307)
the redirected request keeps the same http verb. http/1.1 behavīor.
從定位請求,
http_status_bad_request (400)
the request could not be processed by the server due to invalid syntax.
因為語法不能被服務器處理
http_status_denied (401)
the requested resource requires user authentication.
請求資源命令必須被驗證(拒絕訪問)
http_status_payment_req (402)
not currently implemented in the http protocol.
沒有完全實現http協議
http_status_forbidden (403)
the server understood the request, but is refusing to fulfill it.
服務器理解了請求,但是拒絕完成他
http_status_not_found (404)
the server has not found anything matching the requested uri (uniform resource identifier).
沒有找到任何被指定的uri
http_status_bad_method (405)
the http verb used is not allowed.
http動作不被允許
http_status_none_acceptable (406)
no resp acceptable to the client were found.
應答沒有被客戶接受
http_status_proxy_auth_req (407)
proxy authentication required.
代理必須被驗證
http_status_request_timeout (408)
the server timed out waiting for the request.
服務器在等待請求時中止了
http_status_conflict (409)
the request could not be completed due to a c with the current state of the resource. the user should resubmit with more information.
請求不能被完成,問題是資源沖突。用戶應該進行調整
http_status_gone (410)
the requested resource is no l available at the server, and no forwarding address is known.
請求的資源在服務器上不再可用,而且沒有轉發地址
http_status_length_required (411)
the server refuses to accept the request without a defined c length.
服務器拒絕接受沒有定義目錄大小的請求
http_status_precond_failed (412)
the prec given in or more of the request header fields evaluated to false when it was tested on the server.
當在服務器上測試請求頭文件放棄一個或者多個請求的條件
http_status_request_too_large (413)
the server is refusing to process a request because the request entity is larger than the server is willing or able to process.
服務器拒絕處理請求,原因是請求的大小超過服務器能夠處理的大小
http_status_uri_too_long (414)
the server is refusing to service the request because the request uri (uniform resource identifier) is l than the server is willing to interpret.
服務器拒絕服務,原因是請求的uri超過了服務器能夠揭示的長度
http_status_unsupported_media (415)
the server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method.
服務器拒絕服務,原因是請求格式不被支持
http_status_retry_with (449)
the request should be retried after doing the appropriate action.
在作了適當的動作后請求被重試
http_status_server_error (500)
the server encountered an unexpected c that prevented it from fulfilling the request.
服務器遇到請求失敗意外
http_status_not_supported (501)
the server does not support the functi required to fulfill the request.
服務器不支持必須完成請求的功能
http_status_bad_gateway (502)
the server, while acting as a gateway or proxy, received an invalid resp from the upstream server it accessed in attempting to fulfill the request.
服務器當作為網關或代理時,從上行服務器接受的響應請求失敗
http_status_service_unavail (503)
the service is temporarily overloaded.
服務器負載
http_status_gateway_timeout (504)
the request was timed out waiting for a gateway.
等待網關時請求斷開,沒有響應
http_status_version_not_sup (505)
the server does not support, or refuses to support, the http protocol version that was used in the request message.
服務器不支持或者拒絕支持正在使用請求的http協議的版本
---------------------
作者:qq_41756364
來源:CSDN
原文:https://blog.csdn.net/qq_41756364/article/details/79982932
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!
---------------------
作者:qq_41756364
來源:CSDN
原文:https://blog.csdn.net/qq_41756364/article/details/79982932
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!