Vue+vux imitation Flying Pig app train ticket section (v)---City list save to MongoDB database and enable the node. JS Service

Source: Internet
Author: User
Tags node server

Save the list of stations to the database and create the service locally

node. JS Create Httpserver

1. Build an express-based operating environment

Global Installation Express-gengerator

CNPM install-g Express-gengerator

2. Create an express project and create a local service

Express Server

Build the server directory, the bin under the directory is an executable file, run the www file under the bin to start the service

Node server/bin/www

Startup successfully opened browser localhost:3000

App.js under Server is a portal file

Configuration of the App.js

varCreateerror = require (' http-errors '));varExpress = require (' Express ');varPath = require (' path ');varCookieparser = require (' Cookie-parser '));varLogger = require (' Morgan ');varEjs = require (' Ejs '));varindex = require ('./routes/index '));varUsers = require ('./routes/users '));varStations = require ('./routes/stations '));varApp =Express ();//View engine SetupApp.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,' Public ')) ; App.use (‘/‘, index); App.use ('/users ', users); App.use ('/stations ', stations);//catch 404 and forward to error handlerApp.use (function(req, res, next) {Next (Createerror (404));});//Error HandlerApp.use (function(Err, req, res, next) {//set locals, only providing error in developmentRes.locals.message =Err.message; Res.locals.error= Req.app.get (' env ') = = = ' Development '?err: {}; //render the error pageRes.status (Err.status | | 500); Res.render (' Error ');}); Module.exports= app;

Installing Mongoose

CNPM Install Mongoose--save

Add a stations.js file under the Routing route folder

varExpress = require (' Express ');varRouter =Express. Router ();varMongoose = require (' Mongoose '));varStations = require ('.. /models/stations ');//Link MongoDB DatabaseMongoose.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;

New models folder under Server folder, new Stations.js file under Models

var mongoose = require (' Mongoose '); var Schema = Mongoose. Schema; var New Schema ({    "Sta_name": String,    "Sta_ename": String,    "Sta_code"  = Mongoose.model (' station ', Stationschema);

Finally, open the localhost:3000/stations to access the station data.

Can be loaded via interface access, Vue with Axios, but there will be a cross-domain problem, under the config file under the Vue project, index.js change Configuration

proxytable: {        '/stations ': {            target:' http://localhost:3000 '}        },

After a series of configurations, you will be able to access the Axios through a pleasant interface.

Vue+vux imitation Flying Pig app train ticket section (v)---City list save to MongoDB database and enable the node. JS Service

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.