根据抓包的方式,获取请求地址来获取火车票信息:
需要的模块:npm install https
https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date=2016-09-01&leftTicketDTO.from_station=ADULT&leftTicketDTO.to_station=BJP&purpose_codes=ADULT
var request = require('request');
var https = require('https');
//获取火车票信息
exports.getTrainInfo = function(req, res) {
var url = '/otn/leftTicket/query?leftTicketDTO.train_date='+req.body.date+'&leftTicketDTO.from_station='+req.body.start+'&leftTicketDTO.to_station='+req.body.end+'&purpose_codes=ADULT';
//生成GET请求的参数
var options = {
hostname: 'kyfw.12306.cn',
port: 443,
path: url,
method: 'GET',
rejectUnauthorized: false
};
var request = https.request(options , function(response){
response.setEncoding("utf8");
var str = '';
//拼接数据流字符串
response.on('data',function(chunk){
str += chunk;
});
response.on('end',function(chunk){
res.json(JSON.parse(str));
});
response.on('error',function(e){
console.log(e.message);
res.json({msg:e.message});
});
request.end();
});
}