在部署項目的時候碰到這麼一個問題:XMLHttpRequest cannot load,下面闡述一下這個問題php
問題背景:html
用nginx+tomcat部署項目。tomcat用的8080端口,nginx用80代理8080端口。項目成功啓動,但凡事涉及到ajax的數據調用所有都報 XMLHttpRequest cannot load的錯nginx
問題緣由:web
因爲同源策略的限制,XmlHttpRequest只容許請求當前源(域名、協議、端口)的資源,只有域名、協議、端口三者都相同纔會被認爲是相同資源,並且ajax自己是不能夠跨域的。而瀏覽器訪問的是80端口、ajax方法訪問的是8080端口,因此就會報錯。ajax
解決方案:跨域
修改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的配置。tomcat
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里加了以下一行代碼cookie