node express 로 rest api를 만들어 볼 것이다. db는 mongodb로 연결해주겠다.
프로젝트 폴더를 만든다.
mkdir server
node 초기화
node init
라이브러리 설치
yarn add express mongoose dotenv helmet morgan nodemon
package.json에서 스크립트 수정
yarn start 할 때 실행할 스크립트 변경
<package.json>
{
"scripts": {
"start": "nodemon index.js"
},
}
mongo cloud에 sign up
https://www.mongodb.com/cloud
Create Organization
Create a Project
Build a Database
free create
Click
Create Cluster
Click
Create User
Click
이러면 mongo db 생성은 완성이 된것이다.
Database Deployments
Connect
Click
Choose a connection method
Click
Connect your application
Click
Add your connection string into your application code
밑에있는 링크 복사
dotenv 사용하기
<index.js>
const dotenv = require("dotenv");
dotenv.config();
아까 복사했던 링크 넣기
<.env>
MONGO_URL = mongodb+srv://<id>:<password>@cluster0.zhc0uyp.mongodb.net/?retryWrites=true&w=majority
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const dotenv = require("dotenv");
dotenv.config();
mongoose.connect(
process.env.MONGO_URL,
{ useNewUrlParser: true, useUnifiedTopology: true },
() => {
console.log("Connected to MongoDB");
}
);
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const helmet = require("helmet");
const morgan = require("morgan");
dotenv.config();
mongoose.connect(
process.env.MONGO_URL,
{ useNewUrlParser: true, useUnifiedTopology: true },
() => {
console.log("Connected to MongoDB");
}
);
// middleware
app.use(express.json());
app.use(helmet());
app.use(morgan("common"));
// 8800 port open
app.listen(8800, () => {
console.log("Backend server is running!");
})
./server
위치에서 routes 폴더 생성
mkdir routes
auth.js 생성
<auth.js>
const router = require("express").Router();
//test
router.get("/test", (req, res) => {
res.send("auth get method");
console.log("test auth get method");
res.status(200).json("test auth successful");
});
//REGISTER
//LOGIN
module.exports = router
같은 방식으로 routes 폴더에 posts.js
users.js
작성
index.js에서 연결해주기
<index.js>
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const helmet = require("helmet");
const morgan = require("morgan");
const userRoute = require("./routes/users");
const authRoute = require("./routes/auth");
const postRoute = require("./routes/posts");
dotenv.config();
mongoose.connect(
process.env.MONGO_URL,
{ useNewUrlParser: true, useUnifiedTopology: true },
() => {
console.log("Connected to MongoDB");
}
);
// middleware
app.use(express.json());
app.use(helmet());
app.use(morgan("common"));
// routing connect
app.use("/api/users", userRoute);
app.use("/api/auth", authRoute);
app.use("/api/posts", postRoute);
// 8800 port open
app.listen(8800, () => {
console.log("Backend server is running!");
})
이렇게 짜고 node index.js
를 실행하면
http://localhost:8800/api/users/test
http://localhost:8800/api/auth/test
http://localhost:8800/api/posts/test
이 곳으로 접속가능하며, test로 써둔 get method들이 실행될것이다.
db schema를 정해주기 위해 ./server
위치에서 models 폴더 생성
mkdir models
User.js
<User.js>
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema(
{
username: {
type: String,
require: true,
min: 3,
max: 20,
unique: true,
},
email: {
type: String,
required: true,
max: 50,
unique: true,
},
password: {
type: String,
required: true,
min: 6,
},
profilePicture: {
type: String,
default: "",
},
coverPicture: {
type: String,
default: "",
},
followers: {
type: Array,
default: [],
},
followings: {
type: Array,
default: [],
},
isAdmin: {
type: Boolean,
default: false,
},
desc: {
type:String,
max:50,
},
city: {
type:String,
max:50,
},
from: {
type:String,
max:50,
},
relationship: {
type:Number,
enum:[1, 2, 3],
},
},
{ timestamps: true }
);
module.exports = mongoose.model("User", UserSchema);
const mongoose = require("mongoose");
const PostSchema = new mongoose.Schema(
{
userId:{
type:String,
required:true
},
desc:{
type:String,
max:500
},
img:{
type:String
},
likes:{
type:Array,
defalut: [],
},
},
{ timestamps: true }
);
module.exports = mongoose.model("Post", PostSchema);
다음 포스트에 이어진다.