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."
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.
response status code and
fields in the response header , and how to
handle exceptions correctly.
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 CodeWe 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:
- GET: Request to obtain the specified resource.
- HEAD: Request the response header of the specified resource.
- POST: Submit data to the specified resource.
- PUT: Request the server to store a resource.
- DELETE: Request the server to delete the specified resource.
- TRACE: Echo the request received by the server, mainly used for testing or diagnosis.
- CONNECT: Reserved in the HTTP/1.1 protocol for proxy servers that can change connections to pipes.
- OPTIONS: Returns the HTTP request method supported by the server.
- GET: Get
- POST: Add
- PUT: Update
- DELETE: Delete
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 server
memory. The front-end interface is as follows:
nbsp;html> <meta> <title>Title</title> <script></script> <script></script> <p> </p><h1 id="Todo-List">Todo List</h1>
- {{ item }}
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中文网!
相关推荐:
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!

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

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

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


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

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

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

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.