后端nodejs的restful接口

柯星辰
2023-12-01
var express = require('express');
app = express();
/**读取body中的json请求数据,前端post请求时发送来的json对象 */
var bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({
    extended: false
}))
app.use(bodyParser.json())
/**
 * 定义返回给客户端的对象
 * @param {pg} code 
 * @param {*} desc 
 * @param {*} data 
 */
var resData = function resData(code,desc,data){
    this.code = code;
    this.desc = desc;
    this.data = data;
}
/**
 * 定义一个person对象
 * @param {p} username 
 * @param {*} password 
 */
var Person = function (username, password) {
    this.username = username
    this.password = password
}
/**
 * 创建一个数组,模拟数据
 */
var persons = [new Person("abc", "123"), new Person("ddd", "456")];
/**
 * 查询用户列表信息
 */
app.get("/user", function (req, res) {
    let response = new resData("200","success",{persons:persons});
    res.json(response)
    
})
/**
 * 获取一个用户信息
 */
app.route("/user/:name").get(function (req, res) {
    console.info(req.params.name)
    var person = persons.filter(function (p) {
        console.info(p.name)
        return p.username == req.params.name
    })
    let response = new resData("200","success",...person);
    res.json(response)

})

/**
 * 新增用户
 */
app.route("/user").post(function (req, res) {
    console.info(req.body.username);
    let response = new resData("200","success","success");
    res.json(response)
})
/**
 * 修改用户
 */
app.route("/user").put(function (req, res) {
    console.info(req.body.id);
    let response = new resData("200","success",req.body.id);
    res.json(response)
})
/**
 * 删除用户
 */
app.route("/user/:id").delete(function (req, res) {
    console.info(req.params.id);
    let response = new resData("200","success",req.params.id);
    res.json(response)
})
/**监听2222端口 */
app.listen(2222)
 类似资料: