跨域問題記錄
阿新 • • 發佈:2018-12-17
問題如上圖,提示說是跨域問題,一直沒有解決,先記錄下
問題描述:.本機執行Vue專案裡有個檔案上傳功能,點選上傳是伺服器根本就沒有收到請求,在不同域下報錯,在同源域下正常執行,其他post請求資料的跨域都正常執行(伺服器端只設定了 context.Response.AddHeader("Access-Control-Allow-Origin", "*");)
網上解決方案一堆,都沒有解決這個問題,以下為網上提供的方案
1.html文件裡增加<meta http-equiv="Access-Control-Allow-Origin" content="*">
2.xhr請求時指定跨域請求時 增加Access-Control-Allow-Origin和withCredentials設定為true
//option的部份程式碼 // option.headers 裡增加 withCredentials :{ default: true//同域名下無效,true 不同域名下需要跨域支援 }, headers:{ default: function () { return { 'Access-Control-Allow-Origin': "http://localhost:8080",//或者指定 * ,有人提到 用*可能還是無法提交請求 ,兩種都試了依然為解決問題 "Access-Control-Allow-Headers":"X-Requested-With,Content-Type", "Access-Control-Allow-Methods":"PUT,POST,GET,DELETE,OPTIONS", "Content-Type":"application/x-www-form-urlencoded;", } } }, //XMLHttpRequest 相關部份程式碼 const xhr = new XMLHttpRequest(); xhr.open('post', action, true); if (option.withCredentials && 'withCredentials' in xhr) { xhr.withCredentials = true; } const headers = option.headers || {}; for (let item in headers) { if (headers.hasOwnProperty(item) && headers[item] !== null) { xhr.setRequestHeader(item, headers[item]); } } xhr.send(formData);
3.伺服器端 也增加 Access-Control-Allow-Origin相關設定
public void ProcessRequest(HttpContext context) { try { WebPublic.LogHelper.WriteLog("comming", "");//這個都沒執行,說明請求根本沒有進來 context.Response.ContentType = "application/json";// "text/plain";這個也沒有用 context.Response.AddHeader("Access-Control-Allow-Origin", "*"); context.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With"); context.Response.AddHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS"); context.Response.AddHeader("Access-Control-Allow-Credentials","true");
4.除錯時,直接將cmd到google瀏覽器根目錄後執行chrome.exe –disable-web-security
參考https://developer.mozilla.org/zh-CN/docs/Web/HTTP/CORS/Errors/CORSMissingAllowOrigin
參考https://blog.csdn.net/china_skag/article/details/42493399
參考https://segmentfault.com/a/1190000011361841