


Detailed explanation of how to create a server using the Nodejs+express module
This article will introduce to you how to create a server using express module in Nodejs. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
Create a server using the express module
Create a new folder with a non-Chinese folder name. The name should not be the same as the module name
npm init -y initialization
-
Download the module, go to the npm official website to search for the module, and use its instructions. Next
- If the download fails, use the command
npm cache clean -f
to clear the cache and download again
- If the download fails, use the command
To use the module, go to the module's official website, or use
// 导入express模块 const express = require("express"); // 创建一个服务器 const app = express(); // 设置返回给用户看的内容 app.get("/", function (req, res) { // 如果是用内置模块http创建的服务器返回的内容用res.end()响应 // 现在我们这里用的是express模块创建的服务器,那用res.send()响应 res.send("Hello World"); }); // 启动服务器 app.listen(4399, () => { console.log("服务器开启了..."); });
in the module description [Related recommendations: "nodejs Tutorial"]
Use express module to create a static resource server
const express = require("express"); const app = express(); // 例如,通过如下代码就可以将 web 目录下的图片、CSS 文件、JavaScript 文件对外开放访问了: app.use(express.static("web")); const port = 8089; // app.get("/", (req, res) => res.send("Hello World!")); app.listen(port, () => console.log(`Example app listening on port ${port}!`));
get/post difference
get value is passed through URL passes value while post passes through request body (guerystring)
The data passed by get is relatively small, while the data passed by post is relatively large
The value passed by get is passed in uri, so the security is low.
The value passed by post is relatively safe - point-
get -Generally used to request data/obtain data
post-Generally used to submit data.eg:
Big event project
Personal center information modification interface: post
Post article interface : post
Get the article interface on page n: get
express implements a simple get interface
/** * 接口:得到一条随机笑话 * 接口地址:/joke * 请求方式:get * 参数:无 * 返回:一条笑话 */ const express = require("express"); const app = express(); app.get("/joke", function (req, res) { // 准备n条笑话(实际开放的时候笑话们肯定是从数据库或者是其他的数据源获取的 let arr = [ "一个男生暗恋一个女生很久了。一天自习课上,男生偷偷的传了小纸条给女生,上面写着“其实我注意你很久了”。不一会儿,女生传了另一张纸条,男生心急火燎的打开一看“拜托你不要告诉老师,我保证以后再也不嗑瓜子了”。。。。。。男生一脸懵逼", "在公园里看到一对很有爱的父女,父亲大约五十岁左右,女儿二十来岁,女儿很乖巧的给爸爸剥了一个茶叶蛋,说说什么互相开怀大笑,好温馨的家庭。但是,为什么后来他们就舌吻了呢?", "有一次和男友吵架了在电话里哭,闺蜜来安慰我,突然,他盯着我的眼睛看。冒出一句:“你的睫毛膏用的什么牌子的,这么哭成这B样,都没掉”。我真是气打不一处来,电话一扔也不哭了。", "昨天因为一件事骂儿子,说你妈妈是猪,你也是头猪。儿子却反过来说我:爸爸你怎么这么衰,娶了一头猪,还生了一只猪!你说你这熊孩子,这是不是找打。", ]; let index = Math.floor(Math.random() * 4); res.send(arr[index]); }); app.listen(4399, () => { console.log("服务器开启了..."); });
express Implement an interface with get parameters
const express = require("express"); const app = express(); app.get("/getNickName", function (req, res) { // 要接收前端传递过来的参数(英雄名) console.log(req.query); // 处理 let heroNickName = ""; switch (req.query.heroName) { case "提莫": heroNickName = "迅捷斥候"; break; case "李青": heroNickName = "盲僧"; break; case "盖伦": heroNickName = "德玛西亚之力"; break; case "亚索": heroNickName = "疾风剑豪"; break; case "阿狸": heroNickName = "九尾妖狐"; break; default: heroNickName = "该英雄不存在"; break; } res.send(heroNickName); }); app.listen(4399, () => { console.log("服务器开启了..."); });
Implement a simple post interface
const express = require("express"); const app = express(); app.post("/sb", function (req, res) { res.send("sb,这是一个post接口"); }); app.listen(4399, () => { console.log("服务器开启了..."); });
Implement a post interface with parameters
/** * 接口:用户登录 * 请求地址:/login * 请求方式:post * 请求参数:username password * 登录账号/用户名 用户密码 * 返回值:登录成功/登录失败 */ const express = require("express"); var bodyParser = require("body-parser"); // 创建服务器 const app = express(); // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: false })); app.post("/login", function (req, res) { // 接收用户传递过来的用户名和密码 // 由于是post方式传递过来的参数,所以用req.query这种方式拿不到 // console.log(req) // console.log(req.query) // 要想获取到通过post传递过来的参数,就要使用第三方模块:body-parser // 就用req.body来获取参数 console.log(req.body); // { username: 'admin', password: '888888' } // 处理 if (req.body.username == "admin" && req.body.password == "888888") { res.send({ code: 200, msg: "登录成功", }); } else { res.send({ code: 400, msg: "账号密码不对", }); } }); app.listen(4399, () => { console.log("服务器开启了..."); });
Returns an interface whose return value is a json format string
/*** * 接口:获取一个实物 * 接口地址:/getFood * 请求方式:get * 返回数据:json */ // 导包 const express = require("express"); // 创建服务器 const app = express(); // 写接口 app.get("/getFood", (req, res) => { // 逻辑处理 // 要去设置一个请求头 res.setHeader("Content-Type", "application/json"); // 返回一个json格式的字符串 res.send(` { "foodName":"红烧肉", "price":50, "description":"好吃,油而不腻" } `); }); // 开启服务器 app.listen(4399, () => { console.log("服务器开启了..."); });
Write an interface for passing file parameters in post mode
/** * 接口:登录接口 * 接口地址:/register * 请求方式:post * 接口参数:username password * 返回值:登录成功/登录失败 */ // 导包 const express = require("express"); const multer = require("multer"); const upload = multer({ dest: "uploads/" }); // 创建服务器 const app = express(); // 写接口 app.post("/register", upload.single("usericon"), (req, res) => { // 传递过来的username,password,usericon如何接收? // 需要使用到一个第三方模块 multer // req.file is the `avatar` file // 传过来的文件,参数名用usericon // req.body will hold the text fields, if there were any // 一起传过来的文本保存在req.body中 console.log(req.file); console.log(req.body); res.send("sb"); }); // 开启服务器 app.listen(4399, () => { console.log("服务器开启了..."); });
For more programming-related knowledge, please visit: Programming Video! !
The above is the detailed content of Detailed explanation of how to create a server using the Nodejs+express module. 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.