nodejs 如何发送带 Cookie 的请求

2017-05-24 20:04:12 +08:00
 imherer

最近接第应用宝支付,其中有个地方要去向 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}
    });
5478 次点击
所在节点    Node.js
1 条回复
lujjjh
2017-05-24 22:42:41 +08:00
Cookie 是用分号分隔的

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

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

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

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

© 2021 V2EX