我正在 OpenShift 上使用 Express 创建一个简单的 Node 应用程序(我只是修改 OpenShift 的默认示例 Node 应用程序)。我想要 CORS 支持:
var cors = require('cors');
...
/**
* Initialize the server (express) and create the routes and register
* the handlers.
*/
self.initializeServer = function() {
self.createRoutes();
self.app = express();
self.app.use(cors());
self.app.use(express.json());
// Add handlers for the app (from the routes).
for (var r in self.routes) {
self.app.get(r, self.routes[r]);
}
self.app.post('/vote/', function (req, res) {
// just echo back the request body
res.json(req.body);
});
};
如果我从本地计算机发送请求,使用 curl 可以正常工作:
C:\Users\Chin\Desktop>curl -H "Content-Type: application/json" -X POST -d "{\"username\":\"xyz\"}" https://bloodbrothers-chinhodado.rhcloud.com/vote/
{"username":"xyz"}
但是,如果我使用 jQuery 从具有不同域的另一个站点发送请求,则返回的正文为空:
$.ajax({
url: "https://bloodbrothers-chinhodado.rhcloud.com/vote/",
type: "POST",
crossDomain: true,
data: JSON.stringify({"username": "xyz"}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response);
},
error: function (xhr, status) {
alert("error");
}
});
=> 服务器返回{}
I put a console.log()
调用里面的self.app.post()
实际上,当请求来自跨域时,请求正文为空。
我在这里做错了什么?该应用程序已上线,因此如果您愿意,您可以尝试自己调用curl 和ajax。
EDIT:在这种情况下,如果我发出 CORS 请求,它确实会进入self.app.post('/vote/', function (req, res) {}
函数(通过输入验证console.log()
在那里打电话)。这是否意味着 CORS 运行良好,问题不是因为 CORS 造成的?