nodejs 集成支付宝能收到 notify 请求但收不到 notify 数据

2015-02-12 10:45:24 +08:00
 lifesurge
鄙人正在集成支付宝即时交易接口
用nodejs+express写的站
提交订单和return url接收都正常,notify url虽能够收到post请求,但是req.body req.query req.params都是空的
自己写代码往notify url 发送POST请求 notify url是能收到数据的

请问,有木有人遇到过类似问题,可能是什么造成的?
7027 次点击
所在节点    程序员
8 条回复
rankjie
2015-02-12 12:20:13 +08:00
如果你检查下 header 和 raw_data 就会发现支付宝的 content-type 有问题(查commit可以看到是去年9月8号我发现了这问题...),发来的 header['content-type'] 是这么个玩意儿:

application/x-www-form-urlencoded; text/html; charset=utf-8

(哪位老师可以指导下为什么是这样的吗?我看w3并没找到有这样的写法)

于是 bodyparser 看不懂这个 content-type,也就没法把数据解析出来

我现在的解决办法就是加个中间件处理下,记得放在bodyparser之前

app.use (req, res, next)->
if req.url is '/api/alipays/notify' and req.get('content-type') is 'application/x-www-form-urlencoded; text/html; charset=utf-8'
req.headers['content-type'] = 'application/x-www-form-urlencoded'
next()
lifesurge
2015-02-12 13:08:52 +08:00
@rankjie 我按照你的方法试了,确实content-type像你所说的那样,但改过以后还是不行啊:

var express = require('express');
var bodyParser = require('body-parser');
var app = express();

app.use(function(req, res, next){
if(req.url == '/alipay/notify' && req.get('content-type') != 'application/x-www-form-urlencoded')
req.headers['content-type'] = 'application/x-www-form-urlencoded';
console.log(req.headers['content-type']); // 打印 application/x-www-form-urlencoded
next();
});

app.use(bodyParser.urlencoded({extended:true}))
app.use(bodyParser.json());
lifesurge
2015-02-12 13:12:26 +08:00
router.post('/alipay/notify', function(req, res){
console.log(req.query);
// 依然是空的
rankjie
2015-02-12 13:16:16 +08:00
把 app.use(bodyParser.json()); 放到 app.use(bodyParser.urlencoded({extended:true})) 上面试试吧...
rankjie
2015-02-12 13:17:40 +08:00
异步通知的数据是POST过来的,没有写在URL里。你取query能取到个蛋啊。。。都在body里啊。
lifesurge
2015-02-12 13:40:13 +08:00
@rankjie 取到啦,太感谢你了
aki_xavier
2015-02-12 14:06:54 +08:00
content-type的这种写法本身是没问题的,bodyparser这个plugin不认也没办法
jinwyp
2015-07-02 15:42:42 +08:00
非常感谢 解决了这个问题

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/170386

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX