Home>Article>Web Front-end> Detailed explanation of how to create a server using the Nodejs+express module

Detailed explanation of how to create a server using the Nodejs+express module

Michael Jordan
Michael Jordan forward
2021-03-24 11:10:07 1929browse

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.

Detailed explanation of how to create a server using the Nodejs+express module

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 commandnpm cache clean -fto clear the cache and download again
  • 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!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete