imherer
V2EX  ›  Node.js

nodejs 如何发送带 Cookie 的请求

  •  
  •   imherer · May 24, 2017 · 5979 views
    This topic created in 3309 days ago, the information mentioned may be changed or developed.

    最近接第应用宝支付,其中有个地方要去向 SDK 服务器发送带 cookie 的请求,不知道什么原因,怎么发都提示{"msg":"missing cookie for request url","ret":-14},用 postman 发送也是同样的错误,代码如下:

     var data = {
            appid: 'wxappid',
            appkey: 'wxappkey',
            openid: 'xxxxx',
            openkey: 'xxxxSmlWBcqGjH1u7yO0C4DgTA',
            ts: Math.floor(new Date().getTime() / 1000),
            pf: 'sdfsdfx2584061791528',
            pfkey: 'sdfsdfd',
            zoneid: '1'
        };
      var cookie_val = 'session_id=' + encodeURIComponent(data.openid) + '&session_type=' + encodeURIComponent(data.openkey) +
            '&org_loc=' + encodeURIComponent('/mpay/get_balance_m');
    // 用这个 data 来计算签名啥的一大堆省略
      data.sig = sign;
        var content = qs.stringify(data);
        var options = {
            hostname: 'ysdktest.qq.com',
            port: 443,
            path: '/mpay/get_balance_m',
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                'Cookie': cookie_val
            }
        };
    
        var req = https.request(options, function (res) {
            console.log('STATUS: ' + res.statusCode);
            console.log('HEADERS: ' + JSON.stringify(res.headers));
            res.setEncoding('utf8');
            res.on('data', function (chunk) {
                console.log('BODY: ' + chunk); // 输出 {"msg":"missing cookie for request url","ret":-14}
            })
        });
        req.on('error', function (e) {
            console.log('problem with request: ' + e.message);
        });
        req.write(content);
        req.end();
    

    GET 和 POST 都试了 都是同样的返回结果 然后我又用了 request 模块

    var url = 'https://ysdktest.qq.com/mpay/get_balance_m?' + qs.stringify(data);
    
        request = request.defaults({jar: true});
        var j = request.jar();
        var cookie = request.cookie(cookie_val);
        j.setCookie(cookie, url);
        request({url: url, jar: j}, function (error, response, body) {
            console.log(body); // {"msg":"missing cookie for request url","ret":-14}
        });
    
    1 replies    2017-05-24 22:42:41 +08:00
    lujjjh
        1
    lujjjh  
       May 24, 2017   ❤️ 2
    Cookie 是用分号分隔的
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1238 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 17:38 · PVG 01:38 · LAX 10:38 · JFK 13:38
    ♥ Do have faith in what you're doing.