Skip to content

Commit

Permalink
[Update]
Browse files Browse the repository at this point in the history
  • Loading branch information
O-h-y-o committed Sep 1, 2023
1 parent 348b875 commit b1fd406
Show file tree
Hide file tree
Showing 14 changed files with 667 additions and 25 deletions.
10 changes: 5 additions & 5 deletions src/.vuepress/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,15 @@ export default defineUserConfig({

locales: {
"/": {
lang: "en-US",
title: "Delicious Jelly",
description: "Give me a jelly",
},
"/ko/": {
lang: "ko-KR",
title: "Delicious Jelly",
description: "Give me a jelly",
},
// "/ko/": {
// lang: "ko-KR",
// title: "Delicious Jelly",
// description: "Give me a jelly",
// },
},

plugins: [
Expand Down
32 changes: 16 additions & 16 deletions src/.vuepress/theme.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,32 +30,32 @@ export default hopeTheme({

locales: {
"/": {
navbar: enNavbar,
sidebar: enSidebar,
footer: "Delicious Jelly",
displayFooter: true,
blog: {
description: "A FrontEnd programmer",
intro: "/intro.html",
},
metaLocales: {
editLink: "Edit this page on GitHub",
},
},

"/ko/": {
navbar: koNavbar,
// navbar: koNavbar,
sidebar: koSidebar,
footer: "Delicious Jelly",
displayFooter: true,
blog: {
description: "프론트엔드 개발자",
intro: "/ko/intro.html",
intro: "/intro.html",
},
metaLocales: {
editLink: "Edit this page on GitHub",
},
},

// "/ko/": {
// navbar: koNavbar,
// sidebar: koSidebar,
// footer: "Delicious Jelly",
// displayFooter: true,
// blog: {
// description: "프론트엔드 개발자",
// intro: "/ko/intro.html",
// },
// metaLocales: {
// editLink: "Edit this page on GitHub",
// },
// },
},

// encrypt: {
Expand Down
2 changes: 1 addition & 1 deletion src/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ layout: BlogHome
icon: home
title: Blog Home
heroImage: /logo.png
heroText: O-h-y-o developement blog
heroText: O-h-y-o Development blog
tagline: Do whatever what I want
heroFullScreen: true

Expand Down
32 changes: 32 additions & 0 deletions src/ko/posts/git/connect-repo.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# 원격 저장소 연결하기

```bash
$ git init
```

초기화를 시켜줍니다.

```bash
$ git remote add origin <REPO_PATH>
```

원격 저장소에 연결시켜줍니다.

```bash
$ git remote -v
```

잘 연결되어있는지 확인해줍니다.

```bash
$ git pull
```

원격 저장소 데이터를 받아줍니다.


```bash
$ git checkout <BRANCH>
```

브랜치를 변경합니다.
98 changes: 96 additions & 2 deletions src/ko/posts/java/connect-mongodb.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,101 @@
# MongoDB 연결하기
# IntelliJ Java Spring boot MongoDB 연결하기

간단하게 자바 스프링부트로 MongoDB에 연결하여 유저가 몇 명 있는지 카운트하는 API를 만들어보겠습니다.

<a href="https://account.mongodb.com/account/login" target="_blank">
mongoDB
MongoDB
</a> 계정이 없다면 만들어주고, 로그인을 해줍니다.

처음 가입하는 것이면 여러가지 질문사항들이 있는데 해당사항에 잘 체크해주고 회원가입을 마쳐주세요.

회원가입을 하면 바로 프로젝트를 만드는 페이지로 이동되는데 여기서도 잘 읽어보고 설정해주세요. 테스트 혹은 개발용이니 M0 무료 티어로 생성해주세요. 추후에 변경 가능하니 고민을 많이할 필요는 없습니다.

프로젝트를 생성했다면 화면 중앙에 생성한 프로젝트가 보일 건데, 이중 Connect를 눌러줍니다. 여러가지 연결 방법이 있는데, 이중 Compass를 이용하겠습니다.

MongoDB Compass 가 설치되어있지 않다면 `I don't have MongoDB Compass installed` 를 선택하여 운영체제에 맞는 버전을 설치해주고, connection string을 입력하여 MongoDB에 연결해줍니다.

설치되어있다면 `I have MongoDB Compass installed` 를 선택하여 connection string을 입력하여 MongoDB에 연결해줍니다.

IntelliJ에서 MongoDB를 사용할 프로젝트에 다음 코드들을 입력해줍니다.

```groovy
// build.gradle
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
}
```

```yml
# ex) src/main/resources/application.yml
spring:
data:
mongodb:
uri: <MongoDB 연결에 사용했던 connection string>/<사용할 데이터베이스 이름>
# ex) mongodb+srv://name:password@<dataBaseID>.mongodb.net/<databaseName>
```

```java
// ex) src/main/java/org/main/repository/UserRepository.java
package org.main.repository;

import org.springframework.data.mongodb.repository.MongoRepository;
import org.main.model.UserModel;

public interface UserRepository extends MongoRepository<UserModel, String> {
}
```

```java
// ex) src/main/java/org/main/service/UserService.java

package org.main.service;

import org.main.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
private final UserRepository userRepository;

@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}

// User 수를 가져오는 함수
public long getTotalUserCount() {
return userRepository.count();
}
}
```

```java
// ex) src/main/java/org/main/controller/UserController.java
package org.main.controller;

import org.main.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.v3.oas.annotations.Operation;


@RestController
@RequestMapping("/api/user")
public class UserController {
private final UserService userService;

@Autowired
public UserController(UserService userService) {
this.userService = userService;
}

@GetMapping("/count")
@Operation(summary = "Get all user count", description = "type: number")
public long getTotalUserCount() {
return userService.getTotalUserCount();
}
}
```

스웨거나 포스트맨 혹은 구현한 웹페이지에서 해당 API를 테스트하면 MongoDB에서 유저의 수를 가져올 수 있습니다.
40 changes: 40 additions & 0 deletions src/ko/posts/java/cors.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# Java Spring boot CORS 허용하기

자바 스프링부트 프로젝트에서 CORS를 허용하는 방법입니다.

```java
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.allowCredentials(true)
.maxAge(3600);
}
}
```

CorsConfig 클래스에서 addCorsMappings() 메서드를 오버라이드하여 CORS 관련 설정을 합니다.

모든 경로("/\*_")에 대해 모든 Origin(allowedOrigins("_"))에서의 GET, POST, PUT, DELETE, OPTIONS 메서드 요청을 허용하도록 설정하고 있습니다.

allowedHeaders("\*")는 모든 허용된 요청 헤더를 나타냅니다.

allowCredentials(true)는 자격 증명(즉, 쿠키, 인증 헤더 등)을 허용하도록 설정합니다.

maxAge(3600)는 프리플라이(pre-flight) 요청의 최대 지속 시간을 설정합니다(여기서는 1시간으로 설정됨).

이제 위에서 만든 CorsConfig 설정이 적용되어 Spring Boot 애플리케이션이 CORS 요청을 허용하게 됩니다.

::: tip

참고: 실제 운영환경에서는 보안을 위해 allowedOrigins를 필요한 도메인으로 한정하는 것이 좋습니다. 위의 예제에서는 allowedOrigins("\*")로 설정하여 모든 Origin으로부터 요청을 허용하도록 하였지만, 실제 운영환경에서는 필요한 도메인만 허용하도록 설정하는 것이 안전합니다.

:::
45 changes: 45 additions & 0 deletions src/ko/posts/nodejs/cors.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Nodejs cors 설정하기

부연설명없이 크게 설정을 많이 하지않으니 바로 코드만 적겠습니다.

```ts
// src/middleware/cors
import { NextFunction, Request, Response } from "express";

const corsMiddleware = (req: Request, res: Response, next: NextFunction) => {
const allowedOrigins = ["url"];

res.header("Access-Control-Allow-Origin", allowedOrigins); // '*'를 넣으면 전체 허용합니다.
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
// header에 다른 값을 허용하고싶으면 추가로 적어주세요.
res.header(
"Access-Control-Allow-Methods",
"GET, PUT, UPDATE, PATCH, POST, DELETE"
);

next();
};

export default corsMiddleware;
```

```ts
// app.ts
import express, { Express } from "express";
import corsMiddleware from "src/middleware/cors";

const app: Express = express();

app.use(corsMiddleware);

// 만약 corsMiddleware에서 설정한 Methods들이 정상적으로 작동되지않으면 아래 코드를 추가해주세요.
app.use(
cors({
origin: "*", // url
methods: ["GET", "POST", "DELETE", "UPDATE", "PUT", "PATCH"],
})
);
```
Loading

0 comments on commit b1fd406

Please sign in to comment.