Home >Web Front-end >JS Tutorial >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.
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.
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>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:
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>Todo List</h1>
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!