最近几天碰到了跨域请求问题,如本地运行程序的url为http://localhost:8090/ide/login_page, 点击页面按钮后需要到http://scheduler.xxx.com:8080/view/bu/wuery/buildWithParameters?token=fe80::c6d9:87ff:fe76:d1e9 请求数据,实际就是调用Jenkins rest api,要求是post方法传参.
我先前用的是jsonp方法解决跨域问题,但是经过实践发现其不支持post请求,只好放弃.
最后发现nginx可以轻松解决ajax的跨域问题.我的网站对应的nginx配置文件如下:
ide_site.conf:
upstream idesitebackend {
server localhost:8085;
}
server {
listen 8090;
server_name localhost;
access_log /opt/ide.log main;
location = /favicon.ico {
log_not_found off;
log_subrequest off;
}
location ^~ /view/ {
proxy_pass http://scheduler.xxx.com:8080;
proxy_set_header Host "scheduler.xxx.com:8080";
}
location ~ ^/(images|script|style|plugin)/ {
root /opt/ide_site/resources;
expires 1d;
}
include ./conf.d/fastcgi.idesite;
}
我post的url为:/ view/bu/wuery/ buildWithParameters?token=fe80::c6d9:87ff:fe76:d1e9
另外我的网站还用了fastcgi, 这里也附上fastcgi的配置文件fastcgi.idesite:
location ~ ^/ide/.*$ {
fastcgi_pass idesitebackend;
fastcgi_split_path_info ^(/ide)(.*)$;
fastcgi_param SCRIPT_FILENAME $fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param SCRIPT_NAME /ide;
fastcgi_param QUERY_STRING $query_string;
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_param CONTENT_TYPE $content_type;
fastcgi_param CONTENT_LENGTH $content_length;
fastcgi_param REQUEST_URI $request_uri;
fastcgi_param DOCUMENT_URI $document_uri;
fastcgi_param DOCUMENT_ROOT $document_root;
fastcgi_param SERVER_PROTOCOL $server_protocol;
fastcgi_param GATEWAY_INTERFACE CGI/1.1;
fastcgi_param SERVER_SOFTWARE nginx;
fastcgi_param REMOTE_ADDR $remote_addr;
fastcgi_param REMOTE_PORT $remote_port;
fastcgi_param SERVER_ADDR $server_addr;
fastcgi_param SERVER_PORT $server_port;
fastcgi_param SERVER_NAME $server_name;
}