node express+mysql搭建简易API服务—body-parser中间件

时间:2021-10-09 10:07:00

最近用express搭建了一个简单的RESTful风格的API服务,数据库使用mysql,主要用于获取数据库数据,模糊搜索等。

需要用到的模块:

  • express:这个都很熟悉了;
  • body-parser:express中间件,用来解析req.body;
  • mysql:用于连接mysql数据库;
1. express启动文件,prod.server.js:
const express = require('express');
const server = require('./mysqlServer');

let port = process.env.PORT || config.build.port;

const app = express();

let router = express.Router();

router.get('/', (req, res, next) => {
    req.url = '/index.html';
    next();
});

app.use(router);

let apiRoutes = express.Router();

apiRoutes.get('/test', (req, res) => {
    server.getData('test', function(errCode, data){
        res.json({
          status: errCode,
          data: data
        });
    });
});
apiRoutes.post('/search', function(req, res) {
    // console.log(req.body);
    server.doSearch(req.body.searchStr, function(errCode, data){
        res.json({
          status: errCode,
          data: data
        });
    });
});

app.use('/api', apiRoutes);

app.use(express.static('./dist'));

module.exports = app.listen(port, function (err) {
    if (err) {
        console.log(err);
        return
    }
    console.log('Listening at http://localhost:' + port + '\n');
});
2. 连接数据库,mysqlServer.js:
const mysql = require('mysql');

const DBConfig = {
    host: 'localhost',
    port: '3306',
    user: 'name',
    password: 'pwd',
    database: '数据库名'
};

exports.getData = function(type, callback) {
    ...
};
exports.doSearch = function(str, callback) {

    let connection = mysql.createConnection(DBConfig);
    connection.connect();

    let sql = "SELECT * FROM xxx WHERE name LIKE '%" + str + "%'";
    // console.log(sql);
    connection.query(sql, function(err, result){
        if(err) {
            console.log('[ERROR SQL] : ', sql);
            console.log('[SEARCH ERROR] - ', err.message);
            callback(0,[]);
        }
        let resultJson = JSON.parse(JSON.stringify(result));
        callback(1,resultJson);
    });

    connection.end();
};
3. 需要注意的是

这里如果就按照我上面这种写法,应该是获取不到POST请求的body的,因为express 4.x官网也说了:

Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as body-parser and multer.

这个意思是提交请求的req.body中的键值对,express接收过来默认是undefined,需要借助中间件来做解析处理,于是便需要用到body-parser

const bodyParser = require('body-parser');

app.use(bodyParser.json()); //for parsing application/json
app.use(bodyParser.urlencoded({ extended: true})); //for parsing application/x-www-form-urlencoded
4. body-parser应用场景

body-parser这两种用法基本覆盖了所有的应用场景,后定义的不会覆盖先定义的,经解析后获取到的都是json格式的对象,刚开始我没写 app.use(bodyParser.urlencoded({ extended: true})); 这一句,req.body可以获取到但是为空对象,这是因为前端提交的默认数据格式是Content-Type:application/x-www-form-urlencoded; charset=UTF-8,因此还需要做进一步解析。

到现在为止,就可以正常调用这个API服务了。