把车站列表保存到数据库,并且从本地创建服务
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(){ 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){ //res.send(‘hello,goods list .‘) Stations.find({}, function(err,doc){ if(err){ res.json({ status:‘1‘, msg:err.message }); }else{ res.json({ status:‘0‘, msg:‘‘, result:{ count:doc.length, list:doc } }) } }) }); module.exports = router;
server文件夹下新建models文件夹,models下新建stations.js文件
var mongoose = require(‘mongoose‘); var Schema = mongoose.Schema; var stationSchema = new Schema({ "sta_name":String, "sta_ename":String, "sta_code":String }); module.exports = mongoose.model(‘Station‘,stationSchema);
最后打开localhost:3000/stations 就可以访问到车站数据了
可以通过接口访问加载了,vue里用axios, 但是这里会存在跨域问题,在vue项目下的config文件下的index.js更改配置
proxyTable: { ‘/stations‘:{ target:‘http://localhost:3000‘ } },
一系列配置之后就能通过axios愉快的访问接口啦~