vue+node+mongoDB 火车票H5(六)---城市列表保存到MongoDB数据库并且启用node.js服务
把车站列表保存到数据库,并且从本地创建服务
node.js创建httpserver
1.搭建基于express的运行环境
全局安装express-gengerator
cnpm install -g express-gengerator
2.创建express项目,创建了本地服务
express server
生成server目录,目录下的bin是可执行文件,运行bin下的www文件启动服务
node server/bin/www
启动成功打开浏览器localhost:3000
server下的app.js是入口文件
app.js的配置
var createError = require('http-errors'); var express = require('express'); var path = require('path'); var cookieParser = require('cookie-parser'); var logger = require('morgan'); var ejs = require('ejs'); var index = require('./routes/index'); var users = require('./routes/users'); var stations = require('./routes/stations'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.engine('.html',ejs.__express); app.set('view engine', 'html'); app.use(logger('dev')); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use('/', index); app.use('/users', users); app.use('/stations', stations); // catch 404 and forward to error handler app.use(function(req, res, next) { next(createError(404)); }); // error handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.render('error'); }); module.exports = app;
安装mongoose
cnpm install mongoose --save
在路由route文件夹下添加stations.js文件
var express = require('express'); var router = express.Router(); var mongoose = require('mongoose'); var Stations = require('../models/stations'); //链接mongodb数据库 mongoose.connect('mongodb://127.0.0.1:27017/train'); mongoose.connection.on("connected", function(res){ console.log("MongoDB connected success."); }); mongoose.connection.on("error", function(){ console.log("MongoDB connected fail."); }); mongoose.connection.on("disconnected", function(){ console.log("MongoDB connected disconnected."); }); router.get("/", function(req,res,next){ Stations.find({}, function(err,doc){ if(err){ res.json({ status:false, msg:err.message }); }else{ res.json({ status:true, msg:'获取车站成功', result:{ count:doc.length, list:doc } }) } }) }); module.exports = router;
server文件夹下新建models文件夹,models下新建stations.js文件
var superagent = require('superagent') var mongoose = require('mongoose'); var Schema = mongoose.Schema; var stationSchema = new Schema({ //新建数据表 "sta_name":String, // 车站名称 "sta_ename":String, // 车站的英文名 "sta_code":String // 车站对应的三字码 }); var monModel = mongoose.model('Station',stationSchema); const url = 'https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.9069' let stalists = [] superagent.get(url) .end(function(response,result){ if (result.statusCode==200) { let r = result.text.split('=')[1] let arr = r.split('@') arr.forEach((i,index)=>{ let list = {} list.sta_name = i.split('|')[1]; list.sta_ename = i.split('|')[3]; list.sta_code = i.split('|')[2]; stalists.push(list); }) monModel.find({},function(err,docs){ console.log(docs.length) if(!docs.length){ // 如果数据库里有数据就不插入,否则就插入数据 // 把车站信息写入数据库 monModel.insertMany(stalists, function(err, docs){ if(err) console.log(err); console.log('车站信息写入成功:' + docs); }); } }) } }) module.exports = monModel;
最后打开localhost:3000/stations 就可以访问到车站数据了
可以通过接口访问加载了,vue里用axios, 但是这里会存在跨域问题,在vue项目下的config文件下的index.js更改配置,在dev下加
proxyTable: { '/stations':{ target:'http://localhost:3000' } },
一系列配置之后就能通过axios愉快的访问接口啦~