获取扫描仪中的信息并传到指定服务器 app.js代码
const http = require('http');
const SerialPort = require("serialport");
const port = new SerialPort('com3');
const fs = require('fs');
var querystring = require('querystring');
const config=JSON.parse(fs.readFileSync('profile.json').toString()).config;
port.on('open',function(){
port.write('main screen turn on ',function(err){
if(err){
return console.log('打开串口失败: ' ,err.message);
}
console.log('打开串口成功');
});
})
port.on('data',function(data){
console.log('Data: '+data);
var data = {'code': data};//这是需要提交的数据
var content = querystring.stringify(data);
var options = config.address
options.path = config.address.path +'?'+ content
var req = http.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);
});
});
req.on('error', function (e) {
console.log('发起请求失败: ' + e.message);
});
req.end();
});
port.on('error',function(err){
console.log('打开串口失败: ',err.message);
})
package.json
{
"name": "HidPos",
"version": "1.0.0",
"main": "app.js",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.16.4",
"serialport": "^9.0.7",
"ws": "^7.4.4"
}
}
profile.json 配置文件的信息
{
"config": {
"scanningGun": "",
"address":{
"hostname": "192.168.0.16",
"port": 8091,
"path": "/login",
"method": "GET"
}
}
}