使用node.js请求https,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| var options = { hostname: "www.baidu.com", port: 443, path: "/bfi-web/api/student/course/list_new", method: "POST", rejectUnauthorized: false, headers: { Accept: "*/*", 'Content-Type': 'text/html; charset=utf-8', Connection: "keep-alive", Host: "www.eluzhu.com", //后台定义的header token: "", version: "1", from: "IDE" } };
var req = https.request(options, function(res) { console.log(`HEADERS: ${JSON.stringify(res.headers)}`); res.setEncoding('utf-8'); var mData = ''; res.on("data", function(d) { console.log('===================================data===========' + d); mData += d; }); res.on("end", function() { var data = JSON.parse(mData); if (data.code == "000000") { //成功处理 } else { vscode.window.showInformationMessage("请求失败:" + data.msg); } }); }); req.end(); req.on("error", function(e) { console.error("====================================================" + e); });
|
1 2 3
| 通过控制台查看console.log(`HEADERS: ${JSON.stringify(res.headers)}`)结果, 查看里面是"content-type":"application/json;charset=utf-8",可以看到后台定义的格式是utf-8; 这里返回什么格式我们就需要用什么格式去解码。
|
最主要方法:res.setEncoding(‘utf-8’);
在网上看到好几种解决乱码的方法都没有效,这次碰到问题记录一下,方便以后别人的需要。