Home > Web Front-end > JS Tutorial > body text

Detailed introduction to implementing Restful style webservice in Node.js

黄舟
Release: 2017-09-29 11:13:10
Original
1464 people have browsed it

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吧!
Copy after login

---------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 } ] }
Copy after login

Define such an object, and then


var routes = require(&#39;./routes&#39;) 
app.use(app.router);//保留原来的 
routes(app);//这个是新加的,将前者作为默认路由
Copy after login
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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!