跳至主要內容

2.2 路由 🎉

刘春龙...大约 2 分钟NODEJSNODE后端express

2.2 路由 🎉

app.method(path, handler)

// 查询所有数据
app.get('/index',  (req, res)=>{
  res.send('查询所有成功');
})
// 增加一条数据
app.post('/index',  (req, res)=>{
  res.send('增加一条成功');
})
//查询一条数据
app.get('/index/1',  (req, res)=>{
  res.send('查询一条成功');
})
//修改一条数据
app.put('/index/1',  (req, res)=>{
  res.send('修改成功');
})
//删除一条数据
app.delete('/index/1',  (req, res)=>{
  res.send('删除成功');
})
const express = require('express');
const bodyParser = require("body-parser");
const sqlFn = require('./mysql')
// 创建Express实例
const app = express();
//接收参数
app.use(bodyParser.urlencoded({ extended: true }))   // application/x-www-form-urlencoded
app.use(bodyParser.json())   // application/json
// 查询所有数据
app.get('/index', (req, res) => {
    var sql = "select * from lea"
    sqlFn(sql, [], (results) => {
        if (results) {
            res.send({
                message: "查询成功",
                result: results
            });
        }
    })
})
// 增加一条数据
app.post('/index', (req, res) => {
    const title = req.body.title
    const main = req.body.main
    const path = req.body.path
    var sql = 'insert into lea (title,main,path) values (?,?,?)'
    sqlFn(sql, [title, main, path], (results) => {
        if (results.affectedRows) {
            res.send({
                message: "增加成功",
                result: results
            });
        }
    })

})
//查询一条数据
app.get('/index/:id', (req, res) => {
    const id = req.params.id
    var sql = "select * from lea where id=?"
    sqlFn(sql, [id], (results) => {
        if (results) {
            res.send({
                message: "查询成功",
                result: results
            });
        }
    })
})
//修改一条数据
app.put('/index/:id', (req, res) => {
    const id = req.params.id
    const title = req.body.title
    const main = req.body.main
    const path = req.body.path
    var sql = "update lea set title=? , main=? , path=? where id=?"
    sqlFn(sql, [title, main, path, id], (results) => {
        if (results.affectedRows) {
            res.send({
                message: "修改成功",
                result: results
            });
        }
    })
})
//删除一条数据
app.delete('/index/:id', (req, res) => {
    const id = req.params.id
    var sql = "delete from lea where id=?"
    sqlFn(sql, [id], (results) => {
        if (results.affectedRows) {
            res.send({
                message: "删除成功",
                result: results
            });
        }
    })
})


// 监听端口
app.listen(3030, function () {
    console.log('服务器正在监听3030端口')
})

参数的获取

上次编辑于:
贡献者: 刘春龙
评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v2.15.7