【发布时间】:2016-05-23 02:16:43
【问题描述】:
我有一个简单的 python 瓶 api,以及一个托管 index.html 的 nginx 服务器,该服务器向在端口 8001 上的本地主机上运行的瓶 api 发出 ajax 请求。问题是我不处理 CORS,因为它在封闭的环境中运行,它只是一个简单的 api 来管理一些活动目录的东西,它位于防火墙和基本身份验证后面。我并不真正担心跨站点脚本。我需要知道的是,如果我从
编写我的 ajax 请求 $.ajax({
type: "GET",
url: "http://localhost:8001/newuser/" + "firstName=" + fname + "&lastName=" + lname + "&email=" + email + "&password=" + new_password,
success: function(data){
alert(data);
document.getElementById("alert").innerHTML = data.toString();
}
});
到
$.ajax({
type: "GET",
url: "/newuser/" + "firstName=" + fname + "&lastName=" + lname + "&email=" + email + "&password=" + new_password,
success: function(data){
alert(data);
document.getElementById("alert").innerHTML = data.toString();
}
});
如何编写 nginx 重写以获取 ajax 请求并使其转到本地主机的端口 8001,如果可能的话。我看了几个例子,但找不到我需要的。
有人可以帮我解决这个问题的 nginx 代码吗,当检测到 /newuser/ 时,我需要将请求转发到 localhost 的 :8001 而不是 :80。
这是因为当我调用 localhost:8001 时,它在 Web 控制台中给了我一个 cors 错误。
我尝试在 nginx 中禁用 CORS
nginx 配置
location * {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
虚拟 nginx 配置
location * {
if ($request_method = 'OPTIONS') {
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';
#
# Tell client that this pre-flight info is valid for 20 days
#
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
if ($request_method = 'POST') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
}
【问题讨论】:
标签: ajax nginx url-rewriting proxy