


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 - pointget -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!

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



Node.js can be used as a backend framework as it offers features such as high performance, scalability, cross-platform support, rich ecosystem, and ease of development.

To connect to a MySQL database, you need to follow these steps: Install the mysql2 driver. Use mysql2.createConnection() to create a connection object that contains the host address, port, username, password, and database name. Use connection.query() to perform queries. Finally use connection.end() to end the connection.

There are two npm-related files in the Node.js installation directory: npm and npm.cmd. The differences are as follows: different extensions: npm is an executable file, and npm.cmd is a command window shortcut. Windows users: npm.cmd can be used from the command prompt, npm can only be run from the command line. Compatibility: npm.cmd is specific to Windows systems, npm is available cross-platform. Usage recommendations: Windows users use npm.cmd, other operating systems use npm.

The following global variables exist in Node.js: Global object: global Core module: process, console, require Runtime environment variables: __dirname, __filename, __line, __column Constants: undefined, null, NaN, Infinity, -Infinity

The main differences between Node.js and Java are design and features: Event-driven vs. thread-driven: Node.js is event-driven and Java is thread-driven. Single-threaded vs. multi-threaded: Node.js uses a single-threaded event loop, and Java uses a multi-threaded architecture. Runtime environment: Node.js runs on the V8 JavaScript engine, while Java runs on the JVM. Syntax: Node.js uses JavaScript syntax, while Java uses Java syntax. Purpose: Node.js is suitable for I/O-intensive tasks, while Java is suitable for large enterprise applications.

Yes, Node.js is a backend development language. It is used for back-end development, including handling server-side business logic, managing database connections, and providing APIs.

Server deployment steps for a Node.js project: Prepare the deployment environment: obtain server access, install Node.js, set up a Git repository. Build the application: Use npm run build to generate deployable code and dependencies. Upload code to the server: via Git or File Transfer Protocol. Install dependencies: SSH into the server and use npm install to install application dependencies. Start the application: Use a command such as node index.js to start the application, or use a process manager such as pm2. Configure a reverse proxy (optional): Use a reverse proxy such as Nginx or Apache to route traffic to your application

Node.js and Java each have their pros and cons in web development, and the choice depends on project requirements. Node.js excels in real-time applications, rapid development, and microservices architecture, while Java excels in enterprise-grade support, performance, and security.
