在部署項目的時候碰到這么一個問題:XMLHttpRequest cannot load,下面闡述一下這個問題
問題背景:
用nginx+tomcat部署項目。tomcat用的8080端口,nginx用80代理8080端口。項目成功啟動,但凡事涉及到ajax的數據調用全部都報 XMLHttpRequest cannot load的錯
問題原因:
由於同源策略的限制,XmlHttpRequest只允許請求當前源(域名、協議、端口)的資源,只有域名、協議、端口三者都相同才會被認為是相同資源,而且ajax本身是不可以跨域的。而瀏覽器訪問的是80端口、ajax方法訪問的是8080端口,所以就會報錯。
解決方案:
修改nginx配置文件,在server中加入如下代碼
server {
listen 80;
server_name www.beib.com;
index index.html index.htm index.php default.html default.htm default.php;
root /home/am/webapps/am;
location / {
add_header 'Access-Control-Allow-Origin' '*';
#
# Om nom nom cookies
#
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
#
# Custom headers and headers various browsers *should* be OK with but aren't
#
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
proxy_pass http://www.beib.com:8080/;
proxy_set_header Host "www.beib.com";
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
問題解決了以后突然發現上傳超過1M大的客戶端文件無法正常上傳,於是修改了下nginx的配置。
server {
listen 80;
server_name www.beib.com;
index index.html index.htm index.php default.html default.htm default.php;
root /home/am/webapps/am;
location / {
add_header 'Access-Control-Allow-Origin' '*';
#
# Om nom nom cookies
#
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
#
# Custom headers and headers various browsers *should* be OK with but aren't
#
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
proxy_pass http://www.beib.com:8080/;
client_max_body_size 1000m;
proxy_set_header Host "www.beib.com";
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
其實只是在location里加了如下一行代碼

