Writing RESTful API interfaces with Node
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)
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')
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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Guide to Table Border in HTML. Here we discuss multiple ways for defining table-border with examples of the Table Border in HTML.

This is a guide to Nested Table in HTML. Here we discuss how to create a table within the table along with the respective examples.

Guide to HTML margin-left. Here we discuss a brief overview on HTML margin-left and its Examples along with its Code Implementation.

Guide to HTML Table Layout. Here we discuss the Values of HTML Table Layout along with the examples and outputs n detail.

Guide to HTML Input Placeholder. Here we discuss the Examples of HTML Input Placeholder along with the codes and outputs.

Guide to the HTML Ordered List. Here we also discuss introduction of HTML Ordered list and types along with their example respectively

Guide to Moving Text in HTML. Here we discuss an introduction, how marquee tag work with syntax and examples to implement.

Guide to HTML onclick Button. Here we discuss their introduction, working, examples and onclick Event in various events respectively.
