如何在Express中解析此HTTP POST请求? [英] How do I parse this HTTP POST request in Express?

查看:203
本文介绍了如何在Express中解析此HTTP POST请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用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请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆