基本使用
这里直接使用app.get
来处理请求
1 2 3 4 5 6 7
| var express = require("source/_posts/Express"); var app = express();
app.get("/", function (req, res) { res.send("hello world"); });
|
项目实例
usersController.js
暴露函数
1 2 3
| module.exports.register = (req, res, next) => { console.log(req.body); };
|
UserRoutes.js
中间件 处理其中一类的请求
1 2 3 4 5 6 7 8 9 10 11
| const { register } = require("../controllers/usersController");
const router = require("source/_posts/Express").Router;
router.post("/register", register);
module.exports = router;
|
index.js
中间件 处理其中一类的请求 挂载 userRoutes 到/api/auth 路径下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| const express = require("source/_posts/Express"); const cors = require("cors");
const mongoose = require("mongoose");
const userRoutes = require("./routes/UserRoutes"); const app = express(); require("dotenv").config();
app.use(cors()); app.use(express.json());
app.use("api/auth", userRoutes);
mongoose .connect(process.env.MONGO_URL, { useNewUrlParser: true, useUnifiedTopology: true, }) .then(() => { console.log("DB Connection Success"); }) .catch((error) => { console.error("Error occured", error.message); });
const server = app.listen(process.env.PORT, () => { console.log(`Server Started on Port ${process.env.PORT}`); });
|