


Detailed 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('/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 Detailed introduction to implementing Restful style webservice in Node.js. For more information, please follow other related articles on the PHP Chinese website!

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.

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

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.

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.

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.

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 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

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.


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

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
Chinese version, very easy to use

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

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
Powerful PHP integrated development environment
