mkdir workspace_express
cd workspace_express
npm init
npm install express
기본 구조
const.js
const SERVER_HOST = "127.0.0.1";
const SERVER_PORT = "5001";
module.exports.SERVER_HOST = SERVER_HOST;
module.exports.SERVER_PORT = SERVER_PORT;
error.js
function errorHandler(req, res) {
const errorObj = {
code: "404",
message: "Error : not found",
};
return res.json(errorObj);
}
module.exports = errorHandler;
home.js
const express = require("express");
const router = express.Router();
const exampleHandler = require("../service/exampleService");
router.post("/example", exampleHandler);
module.exports = router;
exampleService.js
function exampleHandler(req, res) {
console.log("hello world");
res.end();
}
module.exports = exampleHandler;
express.js
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const routeHome = require("./router/home");
const routerError = require("./router/error");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use("/", routeHome);
app.use(routerError);
module.exports = app;
index.js
const { SERVER_HOST,SERVER_PORT } = require("./const/const");
const expressApp = require("./express");
expressApp.listen(SERVER_PORT,SERVER_HOST,()=>{
console.log(`server start`);
})
node index.js