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

Writing RESTful API interfaces with Node

不言
Release: 2018-07-07 18:00:09
Original
3661 people have browsed it

This article mainly introduces the use of Node to write RESTful API interfaces, which has certain reference value. Now I share it with everyone. Friends in need can refer to it.

Preface

This article will Through a small project with a todo list that separates the front and back ends, we will explain how to use Node to create a RESTful-style API interface.

Create HTTP server

Let’s first learn how to create an HTTP server with Node (familiar readers can skip it directly).
It is very convenient to create an HTTP server with Node. To create an HTTP server, you need to call the http.createServer() function. It has only one parameter, which is a callback function. The server will call it every time it receives an HTTP request. this callback function. This callback will receive two parameters, the request and response objects, usually abbreviated as req and res:

var http = require('http')
var server = http.createServer(function(req, res){
   res.end('Hello World')
})
server.listen(3000, '127.0.0.1')
Copy after login

Run the above code and visit http://localhost:3000## in the browser #. You should then see a plain text page containing "Hello World."

Every time the server receives an HTTP request, it will use new req and res objects

to trigger the callback function. Before triggering the callback function, Node will parse the HTTP headers of the request and provide them to the request callback as part of the req object. But Node will not start parsing the request body before the callback function is triggered. This approach is different from some server-side frameworks. For example, PHP parses the request header and request body before the program logic is run.

Node will not automatically write any response to the client. After calling the request callback function, it is your responsibility to end the response using the res.end() method (see the figure below). This way you can run any asynchronous logic you want during the lifetime of the request before ending the response. If you fail to end the response, the request will hang until the client times out, or it will remain open.


Writing RESTful API interfaces with Node

Building an HTTP server is just the beginning. Next, let's take a look at how to set the

response status code and fields in the response header , and how to handle exceptions correctly.

Set the response header

You can use

res.setHeader(field, value) to set the corresponding response header. The following is the code:

var http = require('http')
var server = http.createServer(function(req, res){
  var body = '<h1>Hello Node</h1>'
  res.setHeader('Content-Length', body.length)
  res.setHeader('Content-Type', 'text/html')
  res.end(body)
})
server.listen(3000)
Copy after login
Setting Status Code

We often need to return HTTP status codes other than the default status code 200. A more common situation is to return a 404 Not Found status code when the requested resource does not exist.

This can be achieved by setting the
res.statusCode property. This property can be assigned a value at any time during the program's response, but before the first call to res.write() or res.end().

var http = require('http')
var server = http.createServer(function(req, res) {
  var body = '<p>页面丢失了</p>'
  res.setHeader('Content-Type', 'text/html;charset=utf-8')
  res.statusCode = 404
  res.end(body)
})
server.listen(3000, '127.0.0.1')
Copy after login
Node’s strategy is to provide a small but powerful network API, unlike frameworks like Rails or Django. Advanced concepts like sessions and basic components like HTTP cookies are not included in Node's core. Those are provided by third-party modules.

Building RESTful Web Services

Dr. Roy Fielding proposed

Representational State Transfer (REST) ​​in 2000. It is an interface style for network applications based on the HTTP protocol. According to regulations, such as GET, POST, PUT and DELETE, respectively correspond to the acquisition, creation, update and deletion of resources.
HTTP protocol defines the following 8 standard methods:

  1. GET: Request to obtain the specified resource.

  2. HEAD: Request the response header of the specified resource.

  3. POST: Submit data to the specified resource.

  4. PUT: Request the server to store a resource.

  5. DELETE: Request the server to delete the specified resource.

  6. TRACE: Echo the request received by the server, mainly used for testing or diagnosis.

  7. CONNECT: Reserved in the HTTP/1.1 protocol for proxy servers that can change connections to pipes.

  8. OPTIONS: Returns the HTTP request method supported by the server.

Creating a standard REST service requires implementing four HTTP verbs. Each predicate covers an operation:

  1. GET: Get

  2. POST: Add

  3. PUT: Update

  4. DELETE: Delete

POST and GET requests

Next, we start writing in RESTful style GET and POST interfaces.

Requirements Analysis

The project decided to adopt

Separation of front and back ends, and the interactive data format is agreed to be json. After the data added by the front end is submitted to the server, The server stores it in servermemory. The front-end interface is as follows:
Writing RESTful API interfaces with Node

First, we write the front-end part.

Front-end part

The front-end part uses the popular vue.js as the framework, and the ajax request uses the axios library. The code is as follows:

nbsp;html>


  <meta>
  <title>Title</title>

  <script></script>
  <script></script>




<p>
  </p><h1>Todo List</h1>
  
Copy after login
        
  • {{ item }}
  •   
      <script> new Vue({ el: &#39;#app&#39;, data: { items: [], item: &#39;&#39; }, created () { axios.get(&#39;http://localhost:3000/&#39;) .then(response => { this.items = response.data }) .catch(function (error) { console.log(error) }) }, methods: { postApi () { axios.post(&#39;http://localhost:3000/&#39;, { item: this.item }) .then(response => { this.items = response.data }) .catch(function (error) { console.log(error) }) } } }) </script> Backend part

The backend part will use

req.method to obtain the HTTP verb of the request and process it according to the situation. code show as below:

var http = require('http')

var items = []

http.createServer(function(req, res) {
  // 设置cors跨域
  res.setHeader('Access-Control-Allow-Origin', '*')
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type')
  res.setHeader('Content-Type', 'application/json')

  switch (req.method) {
    // 设置了cors跨域
    // post请求时,浏览器会先发一次options请求,如果请求通过,则继续发送正式的post请求
    case 'OPTIONS':
      res.statusCode = 200
      res.end()
      break

    case 'GET':
      let data = JSON.stringify(items)
      res.write(data)
      res.end()
      break

    case 'POST':
      let item = ''
      req.on('data', function (chunk) {
        item += chunk
      })
      req.on('end', function () {
        // 存入
        item = JSON.parse(item)
        items.push(item.item)
        // 返回到客户端
        let data = JSON.stringify(items)
        res.write(data)
        res.end()
      })
      break
  }
}).listen(3000)

console.log('http server is start...')
Copy after login

小结

当然,一个完整的RESTful服务还应该实现PUT谓词和DELETE谓词,如果你真的读懂了本文,那么相信这对你已经不再是问题了。

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

async/await 并行请求和错误处理

node爬取拉勾网数据并导出为excel文件

The above is the detailed content of Writing RESTful API interfaces with Node. 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!