π bezkoder
https://www.bezkoder.com/react-node-express-mongodb-mern-stack/
Node.js + mongoDB
1. ν΄λ νλλ₯Ό λ§λ€κ³ ν΄λΉ μμΉμμ vs codeλ₯Ό μ°λ€
2. ctrl + ` λλ¬μ ν°λ―Έ μ΄κ³ μλ λͺ λ Ήμ΄ μ λ ₯
npm install express mongoose body-parser cors --save
3. λ£¨νΈ ν΄λμμ server.js νμΌ μμ± ν μλμ κ°μ΄ μ½λ μ λ ₯
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
var corsOptions = {
origin: "http://localhost:8081"
};
app.use(cors(corsOptions));
// parse requests of content-type - application/json
app.use(bodyParser.json());
// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// simple route
app.get("/", (req, res) => {
res.json({ message: "Welcome to bezkoder application." });
});
// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
4. ν°λ―Έλμμ node server.js λͺ λ Ήμ΄ μ€ν
μ΄ λ Error: listen EADDRINUSE: address already in use :::8080 κ³Ό κ°μ μλ¬κ° λ μ μλλ°, κ·Έλ₯ ν΄λΉ ν¬νΈκ° μ¬μ© μ€μ΄λΌλ λ§μ΄λ―λ‘ portλ₯Ό μΈν ν λ 8080 λμ λ€λ₯Έ μ«μλ₯Ό μ¬μ©νλ©΄ λλ€. (ex. 8090)
5. appν΄λ μμ± ν app/config/db.config.js νμΌ μμ±
module.exports = {
url: "mongodb://localhost:27017/bezkoder_db"
};
μ΄ λ λ²μ μ΄ 17.x μ΄μμ΄λ©΄ urlμ localhost λμ 127.0.0.1μ μ¨μΌν¨
6. app/models/index.js νμΌ μμ±
const dbConfig = require("../config/db.config.js");
const mongoose = require("mongoose");
mongoose.Promise = global.Promise;
const db = {};
db.mongoose = mongoose;
db.url = dbConfig.url;
db.tutorials = require("./tutorial.model.js")(mongoose);
module.exports = db;
6-1. server.js νμΌ λ΄μμ connect() ν¨μ νΈμΆ (κΈ°μ‘΄ λ΄μ©μ μλ μ½λλ§ λ§λΆμ΄λ©΄ λ¨)
...
const app = express();
app.use(...);
const db = require("./app/models");
db.mongoose
.connect(db.url, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log("Connected to the database!");
})
.catch(err => {
console.log("Cannot connect to the database!", err);
process.exit();
});
7. app/models/tutorial.model.js νμΌ μμ±
module.exports = mongoose => {
const Tutorial = mongoose.model(
"tutorial",
mongoose.Schema(
{
title: String,
description: String,
published: Boolean
},
{ timestamps: true }
)
);
return Tutorial;
};
μ΄ λ νλ‘ νΈμλμ ν¨κ» μ΄ μ±μ μ¬μ©ν κ±°λΌλ©΄ _id λμ idλ₯Ό μ¬μ©ν΄μΌ νλ―λ‘ toJSON λ©μλ μ€λ²λΌμ΄λ νμ
module.exports = mongoose => {
var schema = mongoose.Schema(
{
title: String,
description: String,
published: Boolean
},
{ timestamps: true }
);
schema.method("toJSON", function() {
const { __v, _id, ...object } = this.toObject();
object.id = _id;
return object;
});
const Tutorial = mongoose.model("tutorial", schema);
return Tutorial;
};
8. app/controllers/tutorial.controller.js νμΌ μμ±
const db = require("../models");
const Tutorial = db.tutorials;
// Create and Save a new Tutorial
exports.create = (req, res) => {
};
// Retrieve all Tutorials from the database.
exports.findAll = (req, res) => {
};
// Find a single Tutorial with an id
exports.findOne = (req, res) => {
};
// Update a Tutorial by the id in the request
exports.update = (req, res) => {
};
// Delete a Tutorial with the specified id in the request
exports.delete = (req, res) => {
};
// Delete all Tutorials from the database.
exports.deleteAll = (req, res) => {
};
// Find all published Tutorials
exports.findAllPublished = (req, res) => {
};
κ° λ©μλ λ΄μ©μ https://www.bezkoder.com/node-express-mongodb-crud-rest-api/ μ°Έμ‘°
(+) νμ΄μ§λ€μ΄μ https://www.bezkoder.com/node-js-mongodb-pagination/
9. app/routes/tutorial.routes.js νμΌ μμ±
module.exports = app => {
const tutorials = require("../controllers/tutorial.controller.js");
var router = require("express").Router();
// Create a new Tutorial
router.post("/", tutorials.create);
// Retrieve all Tutorials
router.get("/", tutorials.findAll);
// Retrieve all published Tutorials
router.get("/published", tutorials.findAllPublished);
// Retrieve a single Tutorial with id
router.get("/:id", tutorials.findOne);
// Update a Tutorial with id
router.put("/:id", tutorials.update);
// Delete a Tutorial with id
router.delete("/:id", tutorials.delete);
// Delete all Tutorials
router.delete("/", tutorials.deleteAll);
app.use('/api/tutorials', router);
};
9-1. server.js νμΌ λ΄μμ routes ν¬ν¨ (app.listen μ§μ μ μ½λ μμ±)
...
require("./app/routes/tutorial.routes")(app);
// set port, listen for requests
const PORT = ...;
app.listen(...);
10. ν°λ―Έλμμ node server.js λͺ λ Ήμ΄ μ€ν
μ£Όμ) mongoDB λ΄μμ λ°μ΄ν°λ² μ΄μ€λ₯Ό μμ±ν ν μ€νν΄μΌ νλ κ² μμ§ λ§κΈ°
11. Postman μ¬μ©νμ¬ ν μ€νΈ (μ νν λ¦¬μΌ μμ±)
κ·Έ μΈ λ©μλλ bezkoder νμ΄μ§ λ΄μμ νμΈν μ μμ
React
λ°±μλ μ½λκ° μ μ₯λμ΄μλ ν΄λ λ§κ³ νλ‘ νΈμλ μ½λλ₯Ό μμ±ν νμΌ λ°λ‘ μμ±
(λ³ΈμΈμ νλ‘μ νΈ ν΄λ λ΄μ backend ν΄λμ frontend ν΄λλ₯Ό λ°λ‘ λμμ)
1. νλ‘μ νΈ ν΄λ λ΄μμ μλ λͺ λ Ήμ΄ μ€ν
npx create-react-app ν΄λλͺ
Import Bootstrap
1. ν΄λΉ ν΄λλ‘ μ΄λ ν μλ λͺ λ Ήμ΄ μ€ν
npm install bootstrap
2. src/App.js νμΌ λ΄μμ import
import React, { Component } from "react";
import "bootstrap/dist/css/bootstrap.min.css";
React Router μΆκ°
1. 컀맨λ μ€ν
npm install react-router-dom
2. src/index.js νμΌ μ€ν ν μλ μ½λλ‘ λ체
import React from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import App from "./App";
const container = document.getElementById("root");
const root = createRoot(container);
root.render(
<BrowserRouter>
<App />
</BrowserRouter>
);
Navbar μΆκ°
1. src/App.js νμΌ μ€ν ν render() λ΄μ μλ μ½λ μμ±
import React, { Component } from "react";
...
class App extends Component {
render() {
return (
<div>
<nav className="navbar navbar-expand navbar-dark bg-dark">
<a href="/tutorials" className="navbar-brand">
bezKoder
</a>
<div className="navbar-nav mr-auto">
<li className="nav-item">
<Link to={"/tutorials"} className="nav-link">
Tutorials
</Link>
</li>
<li className="nav-item">
<Link to={"/add"} className="nav-link">
Add
</Link>
</li>
</div>
</nav>
<div className="container mt-3">
<Routes>
<Route path="/" element={<TutorialsList/>} />
<Route path="/tutorials" element={<TutorialsList/>} />
<Route path="/add" element={<AddTutorial/>} />
<Route path="/tutorials/:id" element={<Tutorial/>} />
</Routes>
</div>
</div>
);
}
}
Initialize Axios for React CRUD HTTP Client
1. 컀맨λ μ€ν
npm install axios
2. src ν΄λ λ΄μ http-common.js νμΌ μμ± ν μλ μ½λ μμ±
import axios from "axios";
export default axios.create({
baseURL: "http://localhost:8080/api",
headers: {
"Content-type": "application/json"
}
});
μ΄ λ baseURLμ backend λ£¨νΈ ν΄λ λ΄ server.js ν¬νΈ λ²νΈμ κ°κ² ν¨
Data service μμ±
- services/tutorial.service.js
import http from "../http-common";
class TutorialDataService {
getAll() {
return http.get("/tutorials");
}
get(id) {
return http.get(`/tutorials/${id}`);
}
create(data) {
return http.post("/tutorials", data);
}
update(id, data) {
return http.put(`/tutorials/${id}`, data);
}
delete(id) {
return http.delete(`/tutorials/${id}`);
}
deleteAll() {
return http.delete(`/tutorials`);
}
findByTitle(title) {
return http.get(`/tutorials?title=${title}`);
}
}
export default new TutorialDataService();
μ»΄ν¬λνΈ μμ±
μλ λ§ν¬ μ°Έκ³
https://www.bezkoder.com/react-crud-web-api/
μ€ν
λ°±μλ μ€ν(node server.js) ν νλ‘ νΈμλ μ€ν (npm start)
μ±κ³΅νλ©΄ μλμΌλ‘ μλμ κ°μ νμ΄μ§κ° λνλ¨
'Node.js' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
[MongoDB/μλ¬] connect econnrefused ::1:27017 (0) | 2023.05.26 |
---|
λκΈ