search
HomeWeb Front-endJS TutorialWriting RESTful API interfaces with Node

Writing RESTful API interfaces with Node

Jul 07, 2018 pm 06:00 PM
axioshtmljavascriptnode.jsvue.js

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

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 id="Hello-Node">Hello Node</h1>'
  res.setHeader('Content-Length', body.length)
  res.setHeader('Content-Type', 'text/html')
  res.end(body)
})
server.listen(3000)
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')
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 id="Todo-List">Todo List</h1>
  
        
  • {{ 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...')

小结

当然,一个完整的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!

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
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python 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 CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C 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 ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript'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 CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The 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 DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding 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 UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python 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 ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

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

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

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.