Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to build a http service in nodejs

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

Nodejs in how to build a http service, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can gain something.

Content Index:

Http module in Node

Using node to build http services

Implement a static resource server

Using template engine to process dynamic web pages

Render dynamic pages with database

Implement a message book case

Third-party HTTP service framework

Http module in Node

Both TCP and UDP are transport layer protocols.

HTTP, which is used to communicate between browser and server, belongs to the application layer protocol because HTTP protocol itself does not consider other issues such as how data is transmitted.

Node provides basic http and https modules for encapsulation of HTTP and HTTPS

Const http = require ('http') const server = http.createServer () 1.1Server instance API description Event:' trigger Event when the close' server shuts down: 'when the request' server receives the request message, trigger server.close () to close the service server.listening to get the service status 1.2 request object API description request.method request method request.url request path request.header request header request.httpVersioni request http protocol version 1.3 response The object API indicates that response.end () ends the response response.setHeader (name Value) set response header response.removeHeader (name, value) delete response header response.statusCode set response status code response.statusMessage set response status phrase response.write () write response data response.writeHead () write response header 2.1 hello worldconst http = require ('http') Const path = require ('path'); const mimie = require (' mime'); / / return the content-typeconst fs = require ('fs') corresponding to the extension; const hostname =' 127.0.0.1 alternate Const port = 3000 X Const server = http.createServer ((req, res) = > {/ / res.setHeader ('Content-type',' text/plain charset=utf-8'); / / response string const url = req.url If (url ='/') {fs.readFile (`. / index.html`, (err, data) = > {if (err) {throw err;} res.statusCode = 200; res.setHeader ('Content-type',' text/html; charset=utf-8'); / / response html res.end (data);}) } else if (url.startsWith ('/ assets/')) {fs.readFile (`. ${url}`, (err, data) = > {if (err) {res.setHeader ('Content-type',' text/plain; charset=utf-8'); res.statusCode = 404; res.end ('404 Not Fund.') } / / path.extname (url) get the file extension const contentType = mimie.getType (path.extname (url)); res.statusCode = 200; res.setHeader ('Content-type', `${contentType}; charset=utf- 8`); / / set the response header res.end (data);});} else {res.statusCode = 404; res.setHeader (' Content-type', 'text/plain Charset=utf-8'); res.end ('404 Not Fund.');} / / console.log (' req', Object.keys (req));}); server.listen (port, hostname, () = > {console.log (`server running at http://${hostname}:${port}`);});)

ContentType comparison table: http://tool.oschina.net/commons

Common template engines:

Marko

Nunjucks

Handlebars.js

Ejs

Pug

Art-template

Template-engine.js

Const http = require ('http'); const path = require (' path'); const fs = require ('fs'); const template = require (' art-template'); const hostname = '127.0.0.1 potential Const port = 3000 Boston Const server = http.createServer ((req, res) = > {const url = req.url; const fileBaseUrl = path.join (_ _ dirname)) If (url = ='/') {fs.readFile ('. / template-engine.html', (err, data) = > {data = data.toString () Const ret = template.render (data, {msg: 'world', todos: [{title:' eat', completed: false}, {title: 'sleep', completed: true}, {title: 'hit Doudou', completed: false}]}); res.setHeader ('Content-type',' text/html charset=utf-8') / / response string z res.end (ret); res.statusCode = 200;});}}); server.listen (port, hostname, () = > {console.log (`server running at http://${hostname}:${port}`);});)

Template-engine.html

Document, it's me {{msg}} {{each todos}} {{$value.title}} {{/ each}} is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report