问题描述
我正在用expressjs构建我的第一个node.js网站.
I'm building my first node.js site with expressjs.
其中的一部分是处理从 Fitbit 到我网站上的终结点/api/1/fitbit_update
的通知,如下所示:
Part of it is handling notifications from Fitbit to an endpoint on my site, /api/1/fitbit_update
, like this one:
POST /api/1/fitbit_update HTTP/1.1
Host: myhost.dk
Content-Type: multipart/form-data; boundary=JGUOAeGT3Fjgjcdk6s35F2mPVVyTdzgR
Content-Length: 374
Connection: keep-alive
--JGUOAeGT3Fjgjcdk6s35F2mPVVyTdzgR
Content-Disposition: form-data; name="updates"; filename="update1353963418000.json"
Content-Type: application/json; charset=UTF-8
Content-Transfer-Encoding: binary
[{"collectionType":"activities","date":"2012-11-26","ownerId":"qw12er23","ownerType":"user","subscriptionId":"112233-activities"}]
--JGUOAeGT3Fjgjcdk6s35F2mPVVyTdzgR--
我需要在HTTP请求的主体中解析json对象,但是Express无法帮助我解决这个问题.
I need to parse the json object in the body of the HTTP request, but Express cannot help me with that.
有什么想法可以持有JSON对象吗?
Any ideas how to get a hold of the JSON object?
我已经看过一些中间件示例,但是我不确定如何真正使用req.on('someevent')方法获取内容.
I've seen some middleware examples, but I'm not sure how to actually get to the contents with the req.on('someevent') approach.
req.body
返回一个空对象{}
req.body
returns an empty object {}
推荐答案
因此,此请求是分段文件上传,其中您感兴趣的文件是JSON文档.查看表达多部分示例.您将想要做类似的事情:
So this request is a multipart file upload where the file you are interested in is a JSON document. Check out the express multipart example. You will want to do something like:
- 在
req.files.updates.path
读取连接已为您保存的文件 - 使用
JSON.parse
将JSON数据解析为对象
- read the file that connect has saved for you at
req.files.updates.path
- parse that JSON data into an object using
JSON.parse
这篇关于如何在Express中解析此HTTP POST请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!