用node写后台接口 (后台管理系统)

3,196 阅读1分钟

第一步 先下载express

引入express 创建服务器

npm install express -S

const express = require('express')const app = express()app.listen(5000, ()=>{ // 打印一下 console.log('http://127.0.0.1:5000')})  

 

第二步 连接数据库

连接数据库需要下载 mysql

- npm install mysql -S -

然后引入mysql 另外req.body需要对表单数据进行解析 所以还需引入body-parser

// 创建数据库连接
const mysql = require('mysql')
const conn = mysql.createConnection({
    host:'localhost',
    user:'root',
    password:'',
    database:'test'
})
// 祖册 解析表单的body-parser
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({extended:false}))

接下来就开始做接口了
先获取数据

// 获取所有的数据
app.get('/api/getheros',(req,res) => {
    // 定义SQL语句
    const sqlStr = 'select * from text where isdel=0'
    conn.query(sqlStr,(err,results) => {
        console.log(results)
        if(err) return res.json({err_code:1,message:'获取失败',affectedRows:0})
        res.json({
            err_code:0,message:results,affectedRows:0
        })
    })

原文地址:blog.csdn.net/xl4277/arti…