V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
• 请不要在回答技术问题时复制粘贴 AI 生成的内容
lifesurge
V2EX  ›  程序员

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

  •  
  •   lifesurge · Feb 12, 2015 · 7928 views
    This topic created in 4100 days ago, the information mentioned may be changed or developed.
    鄙人正在集成支付宝即时交易接口
    用nodejs+express写的站
    提交订单和return url接收都正常,notify url虽能够收到post请求,但是req.body req.query req.params都是空的
    自己写代码往notify url 发送POST请求 notify url是能收到数据的

    请问,有木有人遇到过类似问题,可能是什么造成的?
    8 replies    2015-07-02 15:42:42 +08:00
    rankjie
        1
    rankjie  
       Feb 12, 2015
    如果你检查下 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
        2
    lifesurge  
    OP
       Feb 12, 2015
    @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
        3
    lifesurge  
    OP
       Feb 12, 2015
    router.post('/alipay/notify', function(req, res){
    console.log(req.query);
    // 依然是空的
    rankjie
        4
    rankjie  
       Feb 12, 2015
    把 app.use(bodyParser.json()); 放到 app.use(bodyParser.urlencoded({extended:true})) 上面试试吧...
    rankjie
        5
    rankjie  
       Feb 12, 2015   ❤️ 1
    异步通知的数据是POST过来的,没有写在URL里。你取query能取到个蛋啊。。。都在body里啊。
    lifesurge
        6
    lifesurge  
    OP
       Feb 12, 2015
    @rankjie 取到啦,太感谢你了
    aki_xavier
        7
    aki_xavier  
       Feb 12, 2015
    content-type的这种写法本身是没问题的,bodyparser这个plugin不认也没办法
    jinwyp
        8
    jinwyp  
       Jul 2, 2015
    非常感谢 解决了这个问题
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   928 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 18:25 · PVG 02:25 · LAX 11:25 · JFK 14:25
    ♥ Do have faith in what you're doing.