今天遇到一個ajax跨域問題,下拉框的數據源要從一個接口獲得,但是該接口被部署到另外一台服務器上,在本地可以通過http請求訪問,並可以返回json的數據,但是放到頁面中不可以獲取到下拉框的值,發現chrome控制台中該請求成功,但是沒有返回值,於是便遇到了跨域的問題,請教一同事,問題得到解決:
1.搭建nginx服務器
下載nginx,我用的是nginx1.0.0,下載之后放到一個目錄中,修改其中的配置文件conf目錄中的ngnix.conf文件
2.找到配置中的server{}標簽,在里面的localtion/{}標簽中添加一句
proxy_pass http://localhost:8080/;
添加后的整體效果為:
1 location / { 2 root html; 3 index index.html index.htm; 4 proxy_pass http://localhost:8080/; 5 }
其中第4行為新加入的
3.在該標簽下自己新建一個標簽,如下:
1 location /partner{ 2 proxy_pass http://10.23.3.31/partner; 3 }
這個proxy_pass http://10.23.3.31/partner就是你要訪問的域
server標簽的整體配置為:
1 server { 2 listen 80; 3 server_name localhost; 4 5 #charset koi8-r; 6 7 #access_log logs/host.access.log main; 8 9 location / { 10 root html; 11 index index.html index.htm; 12 proxy_pass http://localhost:8080/; 13 } 14 location /partner{ 15 proxy_pass http://10.23.3.31/partner; 16 } 17 18 #error_page 404 /404.html; 19 20 # redirect server error pages to the static page /50x.html 21 # 22 error_page 500 502 503 504 /50x.html; 23 location = /50x.html { 24 root html; 25 } 26 27 # proxy the PHP scripts to Apache listening on 127.0.0.1:80 28 # 29 #location ~ \.php$ { 30 # proxy_pass http://127.0.0.1; 31 #} 32 33 # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 34 # 35 #location ~ \.php$ { 36 # root html; 37 # fastcgi_pass 127.0.0.1:9000; 38 # fastcgi_index index.php; 39 # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; 40 # include fastcgi_params; 41 #} 42 43 # deny access to .htaccess files, if Apache's document root 44 # concurs with nginx's one 45 # 46 #location ~ /\.ht { 47 # deny all; 48 #} 49 }
其中12、14、15、16行為自己手動添加的
修改完畢后,啟動nginx.exe程序
注意,此時訪問的路徑會發生變化,不需要帶端口號,如果之前的訪問為:localhost:8080//oss-api-server...
現在需要改為:localhost//oss-api-server...即可得到從別的域中取回來的數據!