本地创建了个客户端,用来post
请求java 的一个数据接口,发现获得的数据中中文部分都是乱码
app.js
完整代码如下:
const Koa = require('koa');
const request = require('request-promise');
const static = require('koa-static');
const path = require('path');
const http = require('http');
const qs = require('querystring');
const Router = require('koa-router');
const app = new Koa();
const port = 9010;
const router = new Router();
app.use(static(path.resolve(__dirname), {
// Try to serve the gzipped version of a file automatically
gzip: true,
// Browser cache max-age in milliseconds.defaults to 0
maxage: 1000 * 3600,
// Allow transfer of hidden files. defaults to false
hidden: false
}));
router.get('/', async (ctx, next)=>{
const data = qs.stringify({
query: 1,
transactionid: 123456,
button1: '+%C8%B7+%B6%A8+'
});
const options = {
protocol : 'http:',
host: "202.109.79.211",
port: 8002,
method: 'POST',
path: '/TransFlowQueryResult.jsp',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
'Content-Length': Buffer.byteLength(data)
}
};
const body = await fetch(options, data);
ctx.type = 'html';
ctx.body = body;
});
app.use(router.routes(), router.allowedMethods());
app.listen(port, ()=>{
console.log('house.guazipu.cn wake up: %s', 'http://localhost:' + port);
});
function fetch(options = {}, payload = {}) {
return new Promise((resolve, reject) => {
const client = http.request(options, (res) => {
res.setEncoding('utf8');
res.on('data', (chunk) => {
resolve(chunk);
})
res.on('end', () => {
console.log('data transfer end');
})
});
client.on('error', (err) => {
reject(err);
});
client.write(payload);
client.end();
});
}
package.json
{
"name": "house",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"license": "ISC",
"dependencies": {
"iconv-lite": "^0.4.19",
"koa": "^2.3.0",
"koa-router": "^7.2.1",
"koa-static": "^4.0.1",
"request": "^2.83.0",
"request-promise": "^4.2.2"
}
}
最终效果:
打了断点,查看数据响应
接口返回的数据是 GBK
做个转码,问题解决
完整代码如下: