我们有一个wordpress网站,该网站由各种不同的域/子域提供服务,我将其称为https://source.example
。我们还在https://destination.example
上有一个Nginx前端的Rails站点。
当有人在https://source.example
上加载页面时,我正尝试向https://destination.example
发送XMLHttpRequest,以告知Rails站点哪个用户正在使用wordpress站点。
目标URL是https://destination.example/accounts/record_activity
,我需要通过POST请求调用它,并在数据中传递{"account_id" : 12345}
。目前,这就是我在source.example
上的javascript中所做的事情:
function recordVipAccountSession(railsSite){
var id = readCookie('token_authed');
if(id != null && readCookie('session_started') == null){
var xhr = new XMLHttpRequest();
//callback for success
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
console.log("got response from xhr POST: "+xhr.responseText);
if(xhr.responseText == "OK"){
//make the cookie, lasting 30 mins (1/48 days), so we don't do this again for another 30 mins
console.log("creating cookie");
createCookie("session_started",(new Date).getTime(),(1.0/48))
} else {
console.log("Didn't get OK back, not setting a cookie");
}
}
}
//set up and send the request
var url = railsSite + "/accounts/record_activity";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
var result = xhr.send("id=" + readCookie("token_authed"));
}
}
最初,请求正在进行,并在Rails端得到处理,但由于(在https://source.example
上报告由于CORS被阻止。因此,我因此更改了nginx配置(这一切都发生在我的开发服务器中):
# in the main 'server' block
# POST requests come from wordpress to this, so allow CORS
location /accounts/record_activity {
add_header 'Access-Control-Allow-Origin' *;
}
通过这种nginx更改,所有内容都不会传递到Rails,并且在源端它现在说(在控制台中) “跨域读取阻止(CORB)阻止了跨域响应{ {3}},MIME类型为text / html“
然后我将nginx配置更改为更具体:
# POST requests come from wordpress to this, so allow CORS
location /accounts/record_activity {
add_header 'Access-Control-Allow-Origin' "$http_origin" always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Allow-Methods' 'POST' always;
add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Requested-With' always;
}
现在,它不再报告CORS问题,而是返回了404文本:在Rails日志中什么也没有发生,所以这大概是来自Nginx:以下是源中对我的xhr请求的响应。示例控制台:
got response from POST: <html>
<head><title>404 Not Found</title></head>
<body bgcolor="white">
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.12.2</center>
</body>
</html>
<!-- a padding to disable MSIE and Chrome friendly error page -->
所以,我想以下一个或两个都是问题:
有人可以看到我在做什么错/没有做什么吗?谢谢