在部署项目的时候碰到这么一个问题: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里加了如下一行代码