使用CORS和OpenShift上的节点应用程序,通过POST来清空请求主体
我正在OpenShift上创build一个简单的Node应用程序,使用快速(我只是修改OpenShift的默认示例节点应用程序)。 我想要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"); } });
=>服务器返回{}
我在self.app.post()
函数中放了一个console.log()
调用,实际上当请求来自跨域时,请求的主体是空的。
我在这里做错了什么? 该应用程序是活的,所以你可以尝试curl和阿贾克斯自称如果你想。
编辑:在这种情况下,如果我做一个CORS请求,它会进入self.app.post('/vote/', function (req, res) {}
函数(通过放入console.log()
那么这是否意味着CORS运行良好,问题不是因为CORS?
我想到了。 事实certificate,启用CORS像我没有工作,因为content-type
是JSON,这使得这个请求“复杂”的要求。 从文档 :
一个简单的跨站请求是:
只使用GET,HEAD或POST。 如果使用POST将数据发送到服务器,则使用HTTP POST请求发送到服务器的数据的Content-Type是application / x-www-form-urlencoded,multipart / form-data或text / plain之一。
不使用HTTP请求设置自定义标题(如X-Modified等)
并从npm cors包doc :
启用CORS预飞行
某些CORS请求被认为是“复杂的”,需要一个初始的OPTIONS请求(称为“飞行前请求”)。 “复杂”CORS请求的示例是使用除GET / HEAD / POST(例如DELETE)以外的HTTP谓词或使用自定义标头的HTTP动词。 要启用预定轨,您必须为要支持的路线添加一个新的选项处理程序:
var express = require('express') , cors = require('cors') , app = express(); app.options('/products/:id', cors()); // enable pre-flight request for DELETE request app.del('/products/:id', cors(), function(req, res, next){ res.json({msg: 'This is CORS-enabled for all origins!'}); });
所以我做了改变,现在运行良好。
- NodeJS / Express PUT请求失败:请求的资源上没有“Access-Control-Allow-Origin”标头
- 虽然Access-Control-Allow-Credentials没有设置,但我得到一个CORS错误
- 使用Angular vs Node.js获取图像尺寸
- 与Express.js和Angular2的CORS
- 当使用angular度$ http请求时,护照req.isAuthenticated始终返回false
- 创buildInstagram API地理订阅的CORS问题
- CORS麻烦与nodejs和AngularJS
- 护照js从跨域login?
- Node.js服务器提供阻止跨源请求