首页 > 代码库 > node.js backend
node.js backend
create a new directory “mytasklist”
set up node.js server
npm init (entry point =>server.js)
open package.json
npm install express body-parser ejs mongojs --save
create server.js file (backend server file)
//run the server with nodemon var express = require(‘express‘); var path = require(‘path‘); var bodyParser = require(‘body-parser‘); var index = require(‘./routes/index‘); //for index home page var tasks = require(‘./routes/tasks‘); //apis work with mongodb var port = 3000; var app = express(); //view engine app.set(‘views‘, path.join(__dirname, ‘views‘)); app.set(‘view engine‘, ‘ejs‘); app.engine(‘html‘, require(‘ejs‘).renderFile); //set static folder, for all angular file app.use(express.static(path.join(__dirname, ‘client‘))); //body parser middle ware app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: false})); app.use(‘/‘, index); app.use(‘/api‘, tasks); app.listen(port, function(){ console.log(‘server started on port ‘+port); });
create ./routes/index.js
var express = require(‘express‘); var router = express.Router(); router.get(‘/‘, function(req, res, next){ res.render(‘index.html‘); }); module.exports = router;
create ./routes/tasks.js
var express = require(‘express‘); var router = express.Router(); router.get(‘/tasks‘, function(req, res, next){ res.send("TASK API"); }); module.exports = router;
create ./views/index.html
<!DOCTYPE html> <html> <head> <title>My Task List</title> </head> <body> <h1>HELLO WORLD!</h1> </body> </html>
npm install -g nodemon
run "nodemon" in the console to start the server
set up mongodb database
login mlab.com
create new -> single-node -> sandbox -> databasename: mytasklist_hardi -> create new mongodb deployment
click on the database -> users -> add database user
click collections tab ->add collection -> name: tasks
click on tasks -> add document
{ "title":"walk the dog" , "isDone": false }
update tasks.js file
go to database page on mlab.com and copy the url, replace the dbuser and dbpassword with yours
var express = require(‘express‘); var router = express.Router(); var mongojs = require(‘mongojs‘); var db = mongojs(‘mongodb://Hardi:asd123@ds161021.mlab.com:61021/mytasklist_hardi‘, [‘tasks‘]); //copy from mlab.com //get all tasks router.get(‘/tasks‘, function(req, res, next){ db.tasks.find(function(err, tasks){ if(err){ res.send(err); } res.json(tasks); }); }); //get single task router.get(‘/task/:id‘, function(req, res, next){ db.tasks.findOne({_id: mongojs.ObjectId(req.params.id)},function(err, task){ if(err){ res.send(err); } res.json(task); }); }); //save task router.post(‘/task‘, function(req, res, next){ var task = req.body; if(!task.title || (task.isDone + ‘‘)){ res.status(400); res.json({ "error": "bad data" }); }else{ db.tasks.save(task, function(err, task){ if(err){ res.send(err); } res.json(task); }); } }); //delete task router.delete(‘/task/:id‘, function(req, res, next){ db.tasks.remove({_id: mongojs.ObjectId(req.params.id)},function(err, task){ if(err){ res.send(err); } res.json(task); }); }); //update task router.put(‘/task/:id‘, function(req, res, next){ var task = req.body; var updTask = {}; if(task.isDone){ updTask.isDone = task.isDone; } if(task.title){ updTask.title = task.title; } if(!updTask){ res.status(400); res.json({ "error": "bad data" }) }else{ db.tasks.update({_id: mongojs.ObjectId(req.params.id)}, updTask, {}, function(err, task){ if(err){ res.send(err); } res.json(task); }); } }); module.exports = router;
参考资料;
- MEAN App From Scratch - MongoDB, Express, Angular 2 & NodeJS
- mlab.com mongoDB
node.js backend
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。