React

 

 

Redux 연동하기

 

버전이 다르기 때문에 소스가 강좌와 다를 수 있다.

버전

next:  13.0.4

antd:  5.0.1

 

소스 : https://github.dev/braverokmc79/node-bird-sns

 

 

 

 

 

 

39. 노드로 서버 구동하기

강의 :

https://www.inflearn.com/course/%EB%85%B8%EB%93%9C%EB%B2%84%EB%93%9C-%EB%A6%AC%EC%95%A1%ED%8A%B8-%EB%A6%AC%EB%89%B4%EC%96%BC/unit/48826?tab=curriculum

 

back/app.js

const http = require('http');
const server = http.createServer((req, res) => {
    console.log(req.url, req.method);


    if (req.method === 'GET') {

    } else if (req.method === 'POST') {

    }

    res.end('Hello node');
});


server.listen(3065, () => {
    console.log("서버 실행 중");
})

 

 

 

 

 

 

 

40. 익스프레스로 라우팅하기

 

강의 :

https://www.inflearn.com/course/%EB%85%B8%EB%93%9C%EB%B2%84%EB%93%9C-%EB%A6%AC%EC%95%A1%ED%8A%B8-%EB%A6%AC%EB%89%B4%EC%96%BC/unit/48827?tab=curriculum

 

$ npm i express

 

 

app.js

const { application } = require('express');
const express = require('express');
const app = express();


// app.get -> 가져오다
// app.post -> 생성하다
// app.put -> 전체 수정
// app.delete -> 제거
// app.patch -> 부분 수정
// app.options -> 찔러보기
// app.head -> 헤더만 가져오기(헤더 / 바디)
//

app.post('/login');  

app.get('/', (req, res) => {
    res.send('hello express');
});

app.get('/api', (req, res) => {
    res.send('hello api');
});


app.get('/api/posts', (req, res) => {
    res.json([
        { id: 1, content: 'hello1' },
        { id: 2, content: 'hello2' },
        { id: 3, content: 'hello3' }
    ])
});



app.post('/api/post', (req, res) => {
    res.json({ id: 1, content: 'hello' })
});


app.delete('/api/post', (req, res) => {
    res.json({ id: 1, content: 'hello' })
});



app.listen(3065, () => {
    console.log("서버 실행 중");
});


 

 

 

 

 

 

 

41. 익스프레스 라우터 분리하기

강의:

https://www.inflearn.com/course/%EB%85%B8%EB%93%9C%EB%B2%84%EB%93%9C-%EB%A6%AC%EC%95%A1%ED%8A%B8-%EB%A6%AC%EB%89%B4%EC%96%BC/unit/48828?tab=curriculum

 

app.js

const express = require('express');
const postRouter = require('./routes/posts');
const app = express();

app.post('/login');
app.get('/', (req, res) => {
    res.send('hello express');
});
app.get('/api', (req, res) => {
    res.send('hello api');
});
app.get('/api/posts', (req, res) => {
    res.json([
        { id: 1, content: 'hello1' },
        { id: 2, content: 'hello2' },
        { id: 3, content: 'hello3' }
    ])
});

app.use('/post', postRouter);

app.listen(3065, () => {
    console.log("서버 실행 중");
});

 

 

routes/posts.js

const express = require('express');
const router = express.Router();



//POST  /post
router.post('/', (req, res) => {
    res.json({ id: 1, content: 'hello' })
});


//DELETE  /post
router.delete('/', (req, res) => {
    res.json({ id: 1 })
});



module.exports = router;

 

 

 

 

 

 

 

42. MySQL과 시퀄라이즈 연결하기

강의 :

https://www.inflearn.com/course/%EB%85%B8%EB%93%9C%EB%B2%84%EB%93%9C-%EB%A6%AC%EC%95%A1%ED%8A%B8-%EB%A6%AC%EB%89%B4%EC%96%BC/unit/48829?tab=curriculum

 

mysql  DB  생성 및 유저생성

create user `react-nodebird`@`localhost` identified by '1234';
create database react_nodebird CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
grant all privileges on react_nodebird.* to `react-nodebird`@`localhost` ;

 

라이브러리 설치

 $ npm i sequelize sequelize-cli  mysql mysql2


 

sequelize   프로젝트 구조 생성

$ npx sequelize init

 

models/index.js  변경

const Sequelize = require("sequelize");
const env = process.env.NODE_ENV || 'development';
const config = require('../config/config')[env];
const db = {}


const sequelize = new Sequelize(config.database, config.username, config.password, config);




Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

 

 

 

 

 

 

 

 

43. 시퀄라이즈 모델 만들기

강의 :

https://www.inflearn.com/course/%EB%85%B8%EB%93%9C%EB%B2%84%EB%93%9C-%EB%A6%AC%EC%95%A1%ED%8A%B8-%EB%A6%AC%EB%89%B4%EC%96%BC/unit/48830?tab=curriculum

 

 

models/comment.js

module.exports = (sequelize, DataTypes) => {
    const Comment = sequelize.define('Comment', {
        //id: {}, id 가 기본적으로 들어있다.
        content: {
            type: DataTypes.TEXT,
            allowNull: false
        },
    }, {
        charset: 'utf8mb4',
        collate: 'utf8mb4_unicode_ci' //이모티콘 저장
    });

    Comment.associate = (db) => { }
    return Comment;
}

 

 

models/hashtag.js

module.exports = (sequelize, DataTypes) => {
    const Hashtag = sequelize.define('Hashtag', {
        //id: {}, id 가 기본적으로 들어있다.
        name: {
            type: DataTypes.STRING(20),
            allowNull: false
        },
    }, {
        charset: 'utf8mb4',
        collate: 'utf8mb4_unicode_ci' //이모티콘 저장
    });

    Hashtag.associate = (db) => { }
    return Hashtag;
}

 

 

 

models/image.js

module.exports = (sequelize, DataTypes) => {
    const Image = sequelize.define('Image', {
        //id: {}, id 가 기본적으로 들어있다.
        src: {
            type: DataTypes.STRING(200),
            allowNull: false
        },
    }, {
        charset: 'utf8mb4',
        collate: 'utf8mb4_unicode_ci' //이모티콘 저장
    });


    Image.associate = (db) => { }
    return Image;
}

 

 

models/post.js

module.exports = (sequelize, DataTypes) => {
    const Post = sequelize.define('Post', { //MYSQL  에는  POST 테이블 생성
        //id: {}, id 가 기본적으로 들어있다.
        content: {
            type: DataTypes.TEXT,
            allowNull: false,
        },
    }, {
        charset: 'utf8mb4',
        collate: 'utf8mb4_unicode_ci' //이모티콘 저장
    });

    Post.associate = (db) => { }
    return Post;
}

 

 

models/user.js

module.exports = (sequelize, DataTypes) => {
    const User = sequelize.define('User', { //MYSQL  에는  users 테이블 생성
        //id: {}, id 가 기본적으로 들어있다.
        email: {
            type: DataTypes.STRING(30),//STRING,TEXT,BOOLEAN,INTEGER,FLOAT,DATETIME
            allowNull: false, //필수,
            unique: true, //고유한 값
        },
        nickname: {
            type: DataTypes.STRING(30),
            allowNull: false, //필수
        },
        password: {
            type: DataTypes.STRING(100),
            allowNull: false,//필수
        }

    }, {
        charset: 'utf8mb4',
        collate: 'utf8mb4_unicode_ci'
    });
    User.associate = (db) => { }
    return User;
}

 

 

 

 

 

 

 

44. 시퀄라이즈 관계 설정하기

강의: 

https://www.inflearn.com/course/%EB%85%B8%EB%93%9C%EB%B2%84%EB%93%9C-%EB%A6%AC%EC%95%A1%ED%8A%B8-%EB%A6%AC%EB%89%B4%EC%96%BC/unit/48831?tab=curriculum

 

models/comment.js

module.exports = (sequelize, DataTypes) => {
    const Comment = sequelize.define('Comment', {
        //id: {}, id 가 기본적으로 들어있다.
        content: {
            type: DataTypes.TEXT,
            allowNull: false
        },
        //UserId:1
        //PostId:3
    }, {
        charset: 'utf8mb4',
        collate: 'utf8mb4_unicode_ci' //이모티콘 저장
    });

    Comment.associate = (db) => {
        db.Comment.belongsTo(db.User);
        db.Comment.belongsTo(db.Post);
    }
    return Comment;
}

 

 

 

models/hashtag.js

module.exports = (sequelize, DataTypes) => {
    const Hashtag = sequelize.define('Hashtag', {
        //id: {}, id 가 기본적으로 들어있다.
        name: {
            type: DataTypes.STRING(50),
            allowNull: false
        },
    }, {
        charset: 'utf8mb4',
        collate: 'utf8mb4_unicode_ci' //이모티콘 저장
    });

    Hashtag.associate = (db) => {
        db.Hashtag.belongsToMany(db.Post);
    }
    return Hashtag;
}

 

 

models/image.js

module.exports = (sequelize, DataTypes) => {
    const Image = sequelize.define('Image', {
        //id: {}, id 가 기본적으로 들어있다.
        src: {
            type: DataTypes.STRING(200),
            allowNull: false
        },
    }, {
        charset: 'utf8mb4',
        collate: 'utf8mb4_unicode_ci' //이모티콘 저장
    });


    Image.associate = (db) => {
        db.Image.belongsTo(db.Post);
    }
    return Image;
}

 

 

models/post.js

module.exports = (sequelize, DataTypes) => {
    const Post = sequelize.define('Post', { //MYSQL  에는  POST 테이블 생성
        //id: {}, id 가 기본적으로 들어있다.
        content: {
            type: DataTypes.TEXT,
            allowNull: false,
        },

        //RetweetId
    }, {
        charset: 'utf8mb4',
        collate: 'utf8mb4_unicode_ci' //이모티콘 저장
    });

    Post.associate = (db) => {
        db.Post.belongsTo(db.User);
        db.Post.belongsToMany(db.Hashtag);
        db.Post.hasMany(db.Comment);
        db.Post.hasMany(db.Image);
        db.Post.belongsToMany(db.User, { through: 'Like', as: 'Likers' });
        db.Post.belongsTo(db.Post, { as: "Retweet" });
    }
    return Post;
}

 

 

 

models/user.js

module.exports = (sequelize, DataTypes) => {
    const User = sequelize.define('User', { //MYSQL  에는  users 테이블 생성
        //id: {}, id 가 기본적으로 들어있다.
        email: {
            type: DataTypes.STRING(30),//STRING,TEXT,BOOLEAN,INTEGER,FLOAT,DATETIME
            allowNull: false, //필수,
            unique: true, //고유한 값
        },
        nickname: {
            type: DataTypes.STRING(30),
            allowNull: false, //필수
        },
        password: {
            type: DataTypes.STRING(100),
            allowNull: false,//필수
        }

        //PostId:1,2,5,10,15
        //CommentId

    }, {
        charset: 'utf8mb4',
        collate: 'utf8mb4_unicode_ci'
    });

    User.associate = (db) => {
        db.User.hasMany(db.Post);
        db.User.hasMany(db.Comment);
        db.User.belongsToMany(db.Post, { through: 'Like', as: 'Liked' });
        db.User.belongsToMany(db.User, { through: 'Follow', as: 'Followers', foreignKey: "FollowingId" });
        db.User.belongsToMany(db.User, { through: 'Follow', as: 'Followings', foreignKey: "FollowerId" });
    };

    return User;
}

 

 

 

 

 

 

 

 

 

45. 시퀄라이즈 sync + nodemon

강의: https://www.inflearn.com/course/%EB%85%B8%EB%93%9C%EB%B2%84%EB%93%9C-%EB%A6%AC%EC%95%A1%ED%8A%B8-%EB%A6%AC%EB%89%B4%EC%96%BC/unit/48832?tab=curriculum

 

 

 

 

models/index.js

const Sequelize = require("sequelize");
const env = process.env.NODE_ENV || 'development';
const config = require('../config/config')[env];
const db = {}


const sequelize = new Sequelize(config.database, config.username, config.password, config);


db.Comment = require('./comment')(sequelize, Sequelize);
db.Hashtag = require('./hashtag')(sequelize, Sequelize);
db.Image = require('./image')(sequelize, Sequelize);
db.Post = require('./post')(sequelize, Sequelize);
db.User = require('./user')(sequelize, Sequelize);



Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

 

 

app.js    models 의 sequelize 추가

const express = require('express');
const postRouter = require('./routes/posts');
const db = require('./models');
const app = express();

db.sequelize.sync()
    .then(() => {
        console.log('db 연결 성공');
    })
    .catch(console.error);


~

 

 

 

테이블 생성 명령어

npx sequelize db:create

 

 

nodemon 설치 

package.json

 "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "nodemon app.js"
  },

 

 

다음과 같이 자동으로  테이블이  생성 된다.

CREATE TABLE `comments` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `content` text COLLATE utf8mb4_unicode_ci NOT NULL,
  `createdAt` datetime NOT NULL,
  `updatedAt` datetime NOT NULL,
  `UserId` int(11) DEFAULT NULL,
  `PostId` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `UserId` (`UserId`),
  KEY `PostId` (`PostId`),
  CONSTRAINT `comments_ibfk_1` FOREIGN KEY (`UserId`) REFERENCES `users` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `comments_ibfk_2` FOREIGN KEY (`PostId`) REFERENCES `posts` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;


CREATE TABLE `follow` (
  `createdAt` datetime NOT NULL,
  `updatedAt` datetime NOT NULL,
  `FollowingId` int(11) NOT NULL,
  `FollowerId` int(11) NOT NULL,
  PRIMARY KEY (`FollowingId`,`FollowerId`),
  KEY `FollowerId` (`FollowerId`),
  CONSTRAINT `follow_ibfk_1` FOREIGN KEY (`FollowingId`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `follow_ibfk_2` FOREIGN KEY (`FollowerId`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;


CREATE TABLE `hashtags` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
  `createdAt` datetime NOT NULL,
  `updatedAt` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;



CREATE TABLE `images` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `src` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL,
  `createdAt` datetime NOT NULL,
  `updatedAt` datetime NOT NULL,
  `PostId` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `PostId` (`PostId`),
  CONSTRAINT `images_ibfk_1` FOREIGN KEY (`PostId`) REFERENCES `posts` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;



CREATE TABLE `like` (
  `createdAt` datetime NOT NULL,
  `updatedAt` datetime NOT NULL,
  `PostId` int(11) NOT NULL,
  `UserId` int(11) NOT NULL,
  PRIMARY KEY (`PostId`,`UserId`),
  KEY `UserId` (`UserId`),
  CONSTRAINT `like_ibfk_1` FOREIGN KEY (`PostId`) REFERENCES `posts` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `like_ibfk_2` FOREIGN KEY (`UserId`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;



CREATE TABLE `posthashtag` (
  `createdAt` datetime NOT NULL,
  `updatedAt` datetime NOT NULL,
  `HashtagId` int(11) NOT NULL,
  `PostId` int(11) NOT NULL,
  PRIMARY KEY (`HashtagId`,`PostId`),
  KEY `PostId` (`PostId`),
  CONSTRAINT `posthashtag_ibfk_1` FOREIGN KEY (`HashtagId`) REFERENCES `hashtags` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `posthashtag_ibfk_2` FOREIGN KEY (`PostId`) REFERENCES `posts` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;



CREATE TABLE `posts` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `content` text COLLATE utf8mb4_unicode_ci NOT NULL,
  `createdAt` datetime NOT NULL,
  `updatedAt` datetime NOT NULL,
  `UserId` int(11) DEFAULT NULL,
  `RetweetId` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `UserId` (`UserId`),
  KEY `RetweetId` (`RetweetId`),
  CONSTRAINT `posts_ibfk_1` FOREIGN KEY (`UserId`) REFERENCES `users` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `posts_ibfk_2` FOREIGN KEY (`RetweetId`) REFERENCES `posts` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;



CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `email` varchar(30) COLLATE utf8mb4_unicode_ci NOT NULL,
  `nickname` varchar(30) COLLATE utf8mb4_unicode_ci NOT NULL,
  `password` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
  `createdAt` datetime NOT NULL,
  `updatedAt` datetime NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;


 

 

 

 

 

 

 

 

 

 

 

 

 

nodejs

 

about author

PHRASE

Level 60  라이트

우선 가정에서 성공하라.

댓글 ( 4)

댓글 남기기

작성