search
HomeWeb Front-endJS TutorialDetailed introduction to 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(&#39;/devices&#39;,function(req, res){ //Restful Get方法,查找整个集合资源 
  res.set({&#39;Content-Type&#39;:&#39;text/json&#39;,&#39;Encodeing&#39;:&#39;utf8&#39;}); 
  res.send(map) 
}) 
app.get(&#39;/devices/:id&#39;,function(req, res){ //Restful Get方法,查找一个单一资源 
  res.set({&#39;Content-Type&#39;:&#39;text/json&#39;,&#39;Encodeing&#39;:&#39;utf8&#39;}); 
  res.send(map[req.param(&#39;id&#39;)]) 
  //console.log(req.param(&#39;id&#39;)) 
}) 
app.post(&#39;/devices/&#39;, express.bodyParser(), function(req, res){ //Restful Post方法,创建一个单一资源 
  res.set({&#39;Content-Type&#39;:&#39;text/json&#39;,&#39;Encodeing&#39;:&#39;utf8&#39;}); 
  map[req.body.id] = req.body 
  res.send({status:"success",url:"/devices/"+req.body.id}) //id 一般由数据库产生 
}) 
app.put(&#39;/devices/:id&#39;, express.bodyParser(), function(req, res){ //Restful Put方法,更新一个单一资源 
  res.set({&#39;Content-Type&#39;:&#39;text/json&#39;,&#39;Encodeing&#39;:&#39;utf8&#39;}); 
  map[req.body.id] = req.body 
  res.send({status:"success",url:"/devices/"+req.param(&#39;id&#39;),device:req.body}); 
}) 
app.delete(&#39;/devices/:id&#39;,function(req, res){ //Restful Delete方法,删除一个单一资源 
  res.set({&#39;Content-Type&#39;:&#39;text/json&#39;,&#39;Encodeing&#39;:&#39;utf8&#39;}); 
  delete map[req.param(&#39;id&#39;)] 
  res.send({status:"success",url:"/devices/"+req.param(&#39;id&#39;)}) 
  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: &#39;/&#39;, 
    method: &#39;get&#39;, 
    callbacks: [Object], 
    keys: [], 
    regexp: /^\/\/?$/i }, 
  { path: &#39;/user/:id&#39;, 
    method: &#39;get&#39;, 
    callbacks: [Object], 
    keys: [{ name: &#39;id&#39;, optional: false }], 
    regexp: /^\/user\/(?:([^\/]+?))\/?$/i } ], 
delete:  
  [ { path: &#39;/user/:id&#39;, 
    method: &#39;delete&#39;, 
    callbacks: [Object], 
    keys: [Object], 
    regexp: /^\/user\/(?:([^\/]+?))\/?$/i } ] }

Define such an object, and then


var routes = require(&#39;./routes&#39;) 
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!


Node.js handles requests, including some other Io, asynchronously and quickly, so I am more optimistic about the performance. Regarding the results of the Ab test, it is still being tested. In short, I hope it can Kill tomcat instantly! (Not a cluster!)

The above is the detailed content of Detailed introduction to implementing Restful style webservice in Node.js. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment