Nodejs开发WEB项目后端接口API(小试牛刀)

项目结构

Nodejs开发WEB项目后端接口API(小试牛刀)_第1张图片

main.js(入口文件,开启9999端口监听,实现RESTful风格接口访问)

const express = require("express");
const app = express();
const port = 9999;//设置端口号,如果端口号被占用需要自己修改,否则无法跑起来(建议不要用80和8080,一般情况都会被占用)
app.listen(port, () => console.log(`http://127.0.0.1:${port}/user/select`));//打印一下接口用例地址
app.use(require("body-parser").json());
app.use(require("body-parser").urlencoded({extended: false}));
//设置跨域访问
app.all("*", function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "*");
    res.header("Access-Control-Allow-Methods", "*");
    res.header("X-Powered-By", "http://www.shuzhiqiang.com");
    res.header("Content-Type", "application/json;charset=utf-8");
    res.header("Access-Control-Allow-Credentials",true);//携带cookie跨域请求
    req.method.toUpperCase() === "OPTIONS" ? res.sendStatus(200) : next();//防止在预请求阶段就响应接口
});
//加入前端需要访问的接口API名称↓↓↓↓
app.use("/user", require("./api/user"));
app.use("/area", require("./api/area"));

api/user.js(业务实现数据查询)

//全局Express框架
const express = require("express");
const router = express.Router();
module.exports = router;

//加载配置文件
const config = require("../config/mysql");
const mysql = require("mysql");
const conn = mysql.createConnection(config);

//查询数据(all方法支持POST、GET、PUT、PATCH、DELETE传参方式)
router.all("/select", (req, res) => {
    // 定义SQL语句
    const id = req.body.id || req.query.id;
    const sqlStr = "select * from user " + (id ? "where id = ?" : "");

    conn.query(sqlStr, id, (err, res) => {
        if (err) return res.json({code: 404, data: "获取失败"});
        res.json({
            code: 0, data: res
        });
    });
});

api/area.js(业务实现数据查询)

//全局Express框架
const express = require("express");
const router = express.Router();
module.exports = router;

//加载配置文件
const config = require("../config/mysql");
const mysql = require("mysql");
const conn = mysql.createConnection(config);

//查询数据(all方法支持POST、GET、PUT、PATCH、DELETE传参方式)
router.all("/select", (req, res) => {
    // 定义SQL语句
    const id = req.body.id || req.query.id;
    const sqlStr = "select * from area " + (id ? "where id = ?" : "");

    conn.query(sqlStr, id, (err, result) => {
        if (err) return result.json({code: 404, data: "获取失败"});
        res.json({
            code: 0, data: result
        });
    });
});

config/mysql.json(数据库配置,支持mysql5.7+)

{
  "host": "localhost",
  "port": "3306",
  "user": "root",
  "password": "root",
  "database": "ycapi"
}

 按照上面的方式创建好项目后,记得在根目录运行:

cnpm i express & cnpm i mysql & node main

启动项目后这样访问:

http://127.0.0.1:9999/user/select

http://127.0.0.1:9999/area/select

就可以查询到数据返回的json结果了,同时也可以用POST或者GET方式传参id

________________________

您还可能对如何用Vue.js框架访问Nodejs后端接口API感兴趣,传送门↓

《Vue.js框架简单读取数据库信息并渲染完成文章列表详情页功能(小试牛刀)》

你可能感兴趣的:(Node.js)