問題如上圖,提示說是跨域問題,一直沒有解決,先記錄下
問題描述:.本機運行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