最近遇到了一個項目,第一次和其餘組的後端合做,因爲域名也是新申請的,因此在合做過程當中遇到了不少跨域的問題。如今本身作一下模擬總結。這裏個人前端使用的vue,後端使用的express。沒有使用vue的proxyTable,就是做爲後端解決一下這個跨域前端
app.all('*', function (req, res, next) { res.header('Access-Control-Allow-Origin', 'http://h5.xesv5.com:8081') res.header('Access-Control-Allow-Credentials', true) res.header("Access-Control-Allow-Headers", "Content-Type,Accept,X-Requested-With,traceid,rpcid") res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS") res.header("Content-Type", "application/json;charset=utf-8") if (req.method == 'OPTIONS') { res.sendStatus(200) } else { if (req.path.indexOf('/getUserInfo') < 0 && (!req.session || !req.session.userInfo)) { res.send({ stat: 1230, message: '登陸失效' }) } else { next() } } })
Response to preflight request doesn't pass access control check: No 'Access-Control-Origin' header is present on the requested resource.
vue
設置Access-Control-Allow-Orign。個人後端一開始只設置了容許http://pylon.xueersi.com域名,可是沒有帶上端口號,帶上端口號便可。ios
當前端設置withCredentials:true時,表示前端容許跨域的後端接口種cookie
express
The value of the 'Access-Control-Allow-Crentials' header in the response is '' which must be 'true' when the request's crentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute
json
後端也須要在請求頭設置Access-Control-Allow-Credentials:trueaxios
Request header field token is not allowed by Access-Control-Allow-Headers in preflight response
後端
若是前端須要在請求頭裏加上token字段,後端這邊須要Access-Control-Allow-Headers設置跨域
res.header("Access-Control-Allow-Headers", "Content-Type,Accept,X-Requested-With,token")
補充:axios請求頭設置參數瀏覽器
config.headers.common['token'] = 123
因爲投放出去的連接是https的,可是以前咱們測試使用的都是http協議的連接。後來改爲https的時候,提示下面的錯誤:Mixed Content: The page at 'https://xxx.com/#/' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint. This request has been blocked: the content must be serverd over HTTPS
安全
個人第一反應其實這也是一個跨域的問題,由於一個是http一個是https,後端只容許了http://xx,沒有容許https協議的連接,可是報的錯誤是Mixed Content,這算是安全策略的報錯,瀏覽器禁止了https協議訪問http協議的資源和接口,大概是瀏覽器首先檢測到的是這個安全策略的問題。
後來我把全部的接口協議修改成:'//xxx.com/xxx'後,繼續報錯,說明這個時候瀏覽器開始進一步檢測跨域的問題:
Response to preflight request doesn't pass access control check: The 'Access-control-Allow-Origin' header has a value 'http://xx.com' that is not equal to the supplied origin.
緣由很簡單:就是跨域的Access-Control-Allow-Origin設置的是http協議的,運維老師加上https的就能夠。