nodejs如何发送带Cookie的请求
最近接第应用宝支付,其中有个地方要去向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}
});
6 回复
推荐用 superagent 加 cookie 的话比如
superagent.post('xxxxx')
.set('Cookie', 'xxxxxx')
// ...
postman 没用过,但是看request的代码,为什么只有cookie而没有其他header? 我一般不用cookie jar request写成这样试试
var option = {
url: yoururl,
headers: {
//some header
'Cookie': cookie_val,
//some header
}
};
request(option,callback);
cookies的是值是&连接吗?我记得是;吧
来自酷炫的 CNodeMD
@zhangmingfeng 是应该用;
@Equim-chan @Yuki-Minakami @zhangmingfeng @zhhb 感谢各位的回复,解决了,果然是cookie连接符的问题 这也太不科学了,虽然我用了&连接,但这样的话我就相当于cookie只传了一个值,它也应该给我报cookie不全啊 😂🤣
先看http