Example of implementing Restful style webservice in Node.js
This article mainly introduces the detailed explanation of using Node.js to implement Restful style webservice. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look.
Restful-style WebService is gradually replacing traditional SOAP. Java also has many Restful frameworks, which are very convenient and concise. Jersey, restlet, and even SpringMVC are also available. I have to say that Rest makes It is easier and more convenient for people to transform from Web to WebService. Of course, if you delve into the theory of Restful, you will find that it is more complicated. However, development and theory do not need to be so consistent. Sometimes pseudo-Restful is more intuitive and reliable.
However, as a very handsome Node.js, how can it not be combined with the equally handsome Restful! ? For developers like us who ignore theory, Restful is just the specification of url + the specification of HTTP method. Therefore, for a very free technology like Node, it is very normal to implement restful as well. No framework is needed, but I still use Express. Express is just a layer of encapsulation of the native http module, so don’t worry about it!
Java used to be a world where Xml configuration files were rampant, but now it is a world where various Annotations have entered. Although annotations are relatively less intrusive, adding a bunch of annotated classes also makes It is frustrating, especially the mixed annotations of various frameworks. Fortunately, the major frameworks are relatively conscious, and each is responsible for different layers, so it will not lead to confusion of various annotations. Okay, then welcome to the world without annotations and xml:
----I am an example---------
var express = require('express') //加载模块
var app = express() //实例化之
var map = {"1":{id:1,name:"test"},"2":{id:2,name:"test"}} //定义一个集合资源,key为字符串完全是模仿java MAP<T,E>,否则谁会这么去写个hash啊!
app.get('/devices',function(req, res){ //Restful Get方法,查找整个集合资源
res.set({'Content-Type':'text/json','Encodeing':'utf8'});
res.send(map)
})
app.get('/devices/:id',function(req, res){ //Restful Get方法,查找一个单一资源
res.set({'Content-Type':'text/json','Encodeing':'utf8'});
res.send(map[req.param('id')])
//console.log(req.param('id'))
})
app.post('/devices/', express.bodyParser(), function(req, res){ //Restful Post方法,创建一个单一资源
res.set({'Content-Type':'text/json','Encodeing':'utf8'});
map[req.body.id] = req.body
res.send({status:"success",url:"/devices/"+req.body.id}) //id 一般由数据库产生
})
app.put('/devices/:id', express.bodyParser(), function(req, res){ //Restful Put方法,更新一个单一资源
res.set({'Content-Type':'text/json','Encodeing':'utf8'});
map[req.body.id] = req.body
res.send({status:"success",url:"/devices/"+req.param('id'),device:req.body});
})
app.delete('/devices/:id',function(req, res){ //Restful Delete方法,删除一个单一资源
res.set({'Content-Type':'text/json','Encodeing':'utf8'});
delete map[req.param('id')]
res.send({status:"success",url:"/devices/"+req.param('id')})
console.log(map)
})
app.listen(8888); //监听8888端口,没办法,总不好抢了tomcat的8080吧!---------I am testing-----------

Use Postman The test is ok. The only surprising thing in the code should be delete map[req.param('id')]. We know that the js map is an Object, or Object is a map. Delete object.property can delete this property. , but delete Object[Property] can also delete this property, delete o.x can also be written as delete o["x"], both have the same effect. For details about delete, please watch: ECMAScript delete!
It’s very convenient to tie it or not! It is very similar to the code of those XXX frameworks! If you are a person looking for something different, Node.js will certainly satisfy you. The routing table that has been controversial has come on stage:
------I am another file: routes. js--------
##
{ get:
[ { path: '/',
method: 'get',
callbacks: [Object],
keys: [],
regexp: /^\/\/?$/i },
{ path: '/user/:id',
method: 'get',
callbacks: [Object],
keys: [{ name: 'id', optional: false }],
regexp: /^\/user\/(?:([^\/]+?))\/?$/i } ],
delete:
[ { path: '/user/:id',
method: 'delete',
callbacks: [Object],
keys: [Object],
regexp: /^\/user\/(?:([^\/]+?))\/?$/i } ] }Define such an object, and then
var routes = require('./routes') app.use(app.router);//保留原来的 routes(app);//这个是新加的,将前者作为默认路由About routes More content: Express official website is more reliable. After all, the biggest problem with node.js is that the data API is too old!
The above is the detailed content of Example of implementing Restful style webservice in Node.js. For more information, please follow other related articles on the PHP Chinese website!
Python vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AMPython is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.
The Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AMC and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.
JavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AMJavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.
JavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AMThe main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.
Understanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AMUnderstanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.
Python vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AMPython is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.
Python vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AMPython and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version
Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.






