NODEJS(6)Expressjs and REST
1. Prepare the dependency
Check the Latest Version
>npm info monk version
npm http GET https://registry.npmjs.org/monk
npm http 304 https://registry.npmjs.org/monk 0.9.0
>pm info express version
4.2.0
I know I will use express as my web frame working to handle the request and dispatcher. Monk to handle the mongodb connection.
So package.json will be as follow>
{
"name": "buglist",
"version": "0.0.1",
"private": true,
"dependencies": {
"express": "4.2.0",
"monk": "0.9.0",
"body-parser": "1.2.0"
}
}
2. How they work together
app.js will use express to listen to a port and serve as http server.
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }))
var bug_module = require('./bug/route');
app.use('/bugs', bug_module);
app.set('port', process.env.PORT || 3001);
app.listen(app.get('port'));
console.log('Running nodeJS on port ' + app.get('port') + ' !');
Router will be handle by express.Router() in route.js in every module
var express = require('express');
var router = express.Router();
var action = require('./action');
/* GET users listing. */
router.get('/', action.getAll);
router.post('/', action.create);
router.get('/:id', action.get);
router.put('/:id', action.update);
router.delete('/:id', action.del);
module.exports = router;
action.js and config.json will handle the connection between request and mongodb, and the limit business logic will be in here.
{
"host": "localhost",
"port": 27010,
"dbname": "buglist"
}
var config = require('../config.json');
var monk = require('monk');
var db = monk(config.host+":"+config.port+'/'+config.dbname);
var collection = db.get('bugs');
// Returns all the bugs
exports.getAll = function(req, res) {
collection.find({}, function(err, bugs){
if (err) res.json(500, err);
else res.json(bugs);
});
};
// Creates a bug
exports.create = function(req, res) {
var body = req.body;
console.log("post body = " + body);
console.log("create title = " + body.title);
console.log("create creation = " + body.creation);
console.log("create status = " + body.status);
console.log("create assignee = " + body.assignee);
collection.insert(body, function(err, bug){
if (err) res.json(500, err);
else res.json(201, bug);
});
};
// Get a bug
exports.get = function(req, res) {
var id = req.params.id;
collection.findById(id, function(err, bug){
if (err) res.json(500, err);
else if (bug) res.json(bug);
else res.send(404);
});
};
// Updates a bug
exports.update = function(req, res) {
var id = req.params.id;
var body = req.body;
delete body._id;
collection.findAndModify({_id: id}, {$set: body}, {multi:false, new:true}, function(err, bug){
if (err) res.json(500, err);
else if (bug) res.json(bug);
else res.send(404);
});
};
// Deletes a bug
exports.del = function(req, res) {
var id = req.params.id;
collection.remove({_id: id}, function(err){
if (err) res.json(500, err);
else res.send(204);
});
};
3. How to Deploy
Command to Start the Server
>DEBUG=express:* node app.js
Show the Debug Message for express and monk
>DEBUG="express:* monk:*" node app.js
Put a port Number in the Command Line
>PORT=3002 DEBUG="express:* monk:*" node app.js
In the app.js, add these things to support that>
app.set('port', process.env.PORT || 3001);
app.listen(app.get('port'));
console.log('Running nodeJS on port ' + app.get('port') + ' !');
Tips:
1. Body Parser Problem.
Error Message>
Most middleware (like bodyParser) is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.
Error: Cannot find module 'body-parser'
Solution>
>npm info body-parser version
npm http GET https://registry.npmjs.org/body-parsernpm http 200 https://registry.npmjs.org/body-parser1.2.0
References:
http://sillycat.iteye.com/admin/blogs/2067546
https://github.com/vdurmont/express-monk-mongodb-example
http://www.vincent-durmont.com/2013/11/29/first-rest-api-with-node-express-monk-and-mongodb.html
body parser document
https://github.com/expressjs/body-parser
monk document
https://github.com/LearnBoost/monk
port number discuss
http://stackoverflow.com/questions/18008620/node-js-express-js-app-only-works-on-port-3000
Make the nodejs app live for ever
https://github.com/nodejitsu/forever
https://github.com/Unitech/pm2
相关推荐
todoAPIjs, NodeJS,ExpressJS和 MongoDB rest式API教程 待办事项Angular,NodeJS,ExpressJS和 MongoDB rest式API教程。 请参见创建一个rest式API教程以获得更详细的信息。安装你只需要安装依赖项:npm install然后...
使用nodejs mongoose / mongodb expressjs的oauth(login)REST API样板 先决条件 GIT,如果没有,您可以使用“下载为zip”选项(感谢github) Nodejs的 Mongodb-如果需要更多时间来设置MongoDB,请使用在线DB( ...
使用NodeJS,ExpressJS,MongoDB,Mongoose,Postman构建RESTFul API 请通过简单地放置一个Github星来支持该项目 :star: 。 :folded_hands: 谢谢 开发环境 1. NodeJS 2. ExpressJS 3. MongoDB Compass 4. Postman...
6. **JSON Web Tokens (JWT)**:为了安全地管理用户身份验证,项目可能使用JWT。JWT是一种轻量级的身份验证机制,可以生成安全的、不可变的令牌,用于在API请求中传递用户信息。 7. **Middleware**:Express中的...
使用AngularJS,NodeJS,ExpressJS和MongoDB的REST API应用 请确保您在本地安装了node.js。 我已经推送了所有依赖项,如果它们出了问题,请删除当前的node_mudule目录,然后使用npm重新安装依赖项。 在运行应用...
简单的RESTjs simpleRESTjs 是一个“简单易用”的基于 nodejs、expressjs 和 mongodb 的 REST Web 服务。 该工具的目标是允许开发人员测试需要将数据存储在云中并保持同步的 Web 和移动应用程序。 是一种简单的方法...
BACKEND - NodeJs, ExpressJS, MongoDb, RestApi PACKAGES - jwt, bcrypt, axios, helmet & express_rate_limit (for security), sharp(image Processing), multer(file upload), nodemailer (sending emails), ...
Nodejs TODO列表API 此应用程序是使用NodeJS,ExpressJs和Mongoose构建的绝对多用户在线Todo管理REST API。 这是一个完整的CRUD应用程序,可帮助您管理待办事项列表。安装克隆存储库:git clone 在/server/config/...
博客RESTful API 这是一个最小的博客API,具有使用NodeJS,ExpressJS和MongoDB开发的一些高级功能。 如果您正在寻找免费的RESTful API进行交互,请随时使用它。 它是开源的。产品特点通过JWT进行身份验证(通过电子...
6. **响应处理**:当API请求完成处理后,返回JSON格式的数据给客户端。这通常包括状态码(如200表示成功,404表示未找到,500表示服务器错误)和响应数据。 7. **错误处理**:确保程序能够优雅地处理异常情况,如...
标题中的“Node.js: Projeto临时NodeJS,ExpressJS,Vue JS,Socket IO,MySQL,MongoDB,TDD和Javascriptavançado”揭示了一个全面的Web开发项目,它利用了一系列现代技术栈。这个项目旨在创建一个基于Node.js的...
电子商务应用一个全栈电子商务应用程序,可将React,Redux,MongoDB,Nodejs,ExpressJS和JWT Authentication与PayPal结合使用,以及Stripe支付系统,该系统允许卖方上传和管理库存,买方可将货物保存到购物车并通过...
这是用于使用ES6,Express和PostgreSQL在Node.js中构建REST API的样板应用程序。 入门 安装 使用https://gitlab.com/trungnq89/nodejs-api.git克隆存储库 使用yarn install安装依赖项(如果请单击此处 在src/config...
**GraphQL** 是Facebook开源的一种查询语言,用于API,解决了传统REST API中过度获取或不足获取数据的问题。通过指定查询结构,GraphQL允许客户端精确地请求所需的数据,从而提高性能并减少网络通信开销。 **React....
BuckUTT-Wall-e BuckUTT Wall-e是由Mousset Axel和Soulier Lucas在2014年为特鲁瓦理工大学的BDE开发的BuckUTT客户。 它由提供REST API和AngularJS前端的NodeJS服务器组成。 这是特鲁瓦工业大学目前正在生产的版本。
6. **错误处理**:在Node.js和Express.js中设置适当的错误处理机制,确保服务的健壮性。 7. **测试**:使用Mocha、Chai等测试框架编写单元测试和集成测试,确保服务的功能正确无误。 8. **版本控制**:使用Git进行...
用nestjs,nodejs,express,monogoodb,猫鼬构建的书店Restful API 一个渐进式的框架,用于构建高效且可扩展的Web应用程序。 描述 框架TypeScript入门资料库。 安装 $ npm install 开始 $ npm run start 人 作者-...
具有Expressjs的REST API的框架 安装 npm install 环境 该API是为在OpenShift上运行而开发的,因此有必要将环境变量配置为在本地运行。 #! /bin/sh export OPENSHIFT_MONGODB_DB_USERNAME= " admin " export ...
6. **JSON数据交换**:在API中,数据通常以JSON(JavaScript Object Notation)格式交换。JSON是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成。 7. **错误处理**:在ExpressJS中,可以...
使用nodejs Express MongoDb构建功能性的REST API,以进一步了解如何通过Mongoose将服务器连接到MongoDB,还可以创建用于定义数据外观的shcemas和模型。 我使用Postman测试我的POST请求API,您可以在这里下载: : ...