以前学过linux服务器上的配置,感觉linux上的比较好用。下面是windows上的详细配置、案例和原理图:
1.背景
我要在本地服务器上的jsp【react】页面上访问聚合网上的数据,但是由于端口、域名、协议的不同导致浏览器识别为跨域请求,因此需要借用nginx的反向代理机制实现跨域请求【其实用jsonp是最简单的方法,但是生产方必须提供必要的回调api】。【什么是跨域】
2.解决方案
使用ngin反向代理实现跨域请求:
nginx.conf配置:
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
#反向代理的配置;
server {
listen 8081;
server_name 127.0.0.1;
#charset koi8-r;
#access_log logs/host.access.log main;
location /juhe {
proxy_pass http://api.shujuzhihui.cn/api/invokingApi/searchExpress?appKey=0c98fbe6005e4c09b398bf9fcaf9cd3d&expressNo=9891754549340;
//------------------必须设置部分---------------------------
proxy_redirect default;
proxy_connect_timeout 1s;
proxy_read_timeout 30s;
proxy_send_timeout 1s;
add_header 'Access-Control-Allow-Headers' 'Content-Type';
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET';
//-------------------必须设置部分--------------------------
index index.html index.htm;
}
}
# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;
# location / {
# root html;
# index index.html index.htm;
# }
#}
# HTTPS server
#
#server {
# listen 443 ssl;
# server_name localhost;
# ssl_certificate cert.pem;
# ssl_certificate_key cert.key;
# ssl_session_cache shared:SSL:1m;
# ssl_session_timeout 5m;
# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on;
# location / {
# root html;
# index index.html index.htm;
# }
#}
}
不要忘了设置请求方式,否则参数的传递可能会出现问题
前端访问案例:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML>
<html>
<head>
<script src="http://libs.baidu.com/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
alert('Hello');
//按钮单击时执行
$("#testAjax").click(function(){
//Ajax调用处理
$.ajax({
type: "POST",
url: "http://127.0.0.1:8081/juhe/",
data: "",
success: function(data){
$("#myDiv").html('<h2>'+data+'</h2>');
}
});
});
});
</script>
</head>
<body>
<div id="myDiv"><h2>通过 AJAX 改变文本</h2></div>
<button id="testAjax" type="button">Ajax改变内容</button>
</body>
</html>
3.根本原理
4.参考文档:Nginx 配置Ajax跨域访问