nodejs-练手项目中get post需求

发布时间 2023-12-22 17:17:33作者: 来菜

这段时间查看微信小程序,看着上面的好多的接口不能用,就想着弄个小接口先用这,顺便复习一下node

首先我们要有必要的npm,node,等基本环境条件

  基本的代码书写:

/* 
    express 是node中的服务器软件
    通过express可以快速的在node中搭建一个web服务器
    -使用步骤:
        1.创建并初始化项目
            yarn init -y
        2.安装express
            yarn add express
        3.创建index.js并编写代码
*/
// 引入express
const express = require("express");
const data = require(“数据的地址”) // 获取服务器的实例(对象) const app = express(); app.get("/hello", (req, res) => {
【访问来获取data数据】 res.send(data) }) app.use("/", (req, res, next) => { console.log("收到请求。。。"); // res.send("这是通过中间件返回的响应") next() })

// 将所有没有输入正确的地址的有一个返回
  app.use((req, res) => {
      res.status(404);
      res.send("<h1>访问地址错误</h1>")
})
/*启动服务器
    app.listen(端口号),用来启动服务器
    端口号用来寻找相应的服务
    [端口号也就相当于一个编号来与其他需要与他相互通信的进程的相互识别和连接]
    服务器启动止呕就可以通过端口号来访问
    协议名://ip:地址:端口号/路径
    http://localhost:3000
    http://127.0.0.1:3000 [这两个表示的是本机和要监听的事件的端口号]
 */
app.listen(3000, () => {
    console.log('start');
})

 这里是post的代码

//用户信息,可以用require获取数据
const USERS = [
    {
        username: "admin",
        password: "123456",
        nickname: "超级管理员"
    }, {
        username: "sunwukong",
        password: "123456",
        nickname: "齐天大圣"
    }
]
app.post('/login', (req, res) => {
        const username = req.body.username;
        const password = req.body.password
        for (const user of USERS) {
            if (user.username === username) {
                // 用户存在检查密码
                if (user.password === password) {
                    res.send('密码正确')
            res.status(200);
return } } } res.send('错误,') )