묻고 답해요
131만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
미해결[코드팩토리] [초급] NestJS REST API 백엔드 완전 정복 마스터 클래스 - Part 1 NestJS Core
JWT refreshToken 쿠키
Client 에서 Refresh Token 을 localStorage 보다는 cookie 에 저장을 하는게 보안에 더 좋다는 이야기를 들었는데요. 만약에 구현을 하려고 하면 강의에서처럼 로그인 했을때 accessToken 과 refreshToken 을 함께 보내는게 아니라 이런식으로 보내면 될까요?res.cookie( 'refreshToken', refreshToken, { httpOnly: true, secure: true, sameSite: 'strict' }); return {accessToken: '엑세스 토큰'};배포 과정과 강의를 담은 Part 2는 언제 나올까요?
-
해결됨Java 마이크로서비스(MSA) 프로젝트 실습
첫번째 MSA 설명 문서 7페이지 model 오타요
잘못써있네용
-
미해결[코드팩토리] [초급] NestJS REST API 백엔드 완전 정복 마스터 클래스 - Part 1 NestJS Core
login에서 token 을 받는 이유가 있을까요?
안녕하세요.토큰시스템을 사용하도록 엔드포인트 변경하기 편을 보고 질문드립니다.보통 login api 라고 하면 token 없이 email, pw 만 받아 validation 하는 것을 목적으로 한다고 알고있는데기획에 따라 헤더의 authorization 필드를 사용한 token 로그인도 해야할 수 있다고 하셔서 궁금한점이 생겼습니다.어떤 경우에 그런 상황이 있는지 대략적인 케이스를 소개해주실수있을까요?강의 잘 보고있습니다. 감사합니다.
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
git hub 업로드가 안되서 여쭤봐요
저같은경우 윈도우를 사용하고 있는데 두가지경우가 나오질 않아서 깃허브에 확인해보니 이렇게 프리캠프는 생성이 되었는데 들어가보니 강의에서 본것처럼 파일이 업로드 되있질 않았어요..어떻게 해야할까요?
-
미해결[코드팩토리] [초급] NestJS REST API 백엔드 완전 정복 마스터 클래스 - Part 1 NestJS Core
Guard 이론 까지 학습 후 질문
안녕하세요.1강~가드이론까지만 학습후 질문드립니다. (파이프강의에서도 안나왔고 뒤에 강의에 왠지 안나올거같아서) 클라이언트 요청이 컨트롤러까지 가면서미들 -> 가드 -> 인터셉터 -> 파이프의 단계를 거친다고 알려주셨는데nest 에서 이렇게 레이어를 나누어둔 이유, 순서가 이렇게된 이유가 있을까요?혹은 사실 하나의 레이어에서 동작하는건데 이해를 돕기위에 이런 단계를 거친다고 개념적으로만 나누어 둔것일까요?
-
미해결[코드팩토리] [초급] NestJS REST API 백엔드 완전 정복 마스터 클래스 - Part 1 NestJS Core
폴더명에 관한 질문인데, 크게 중요하진 않을 것 같긴한데
보통 nest g resource 명령어로 생성한곳에 entity를 생성 할때 복수형으로 entities로 만드셨었는데, common resource에서는 entity 폴더로 만드신 따로 이유가 있으신걸까용?
-
미해결[코드팩토리] [초급] NestJS REST API 백엔드 완전 정복 마스터 클래스 - Part 1 NestJS Core
nest에서 throw시
- 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! - 먼저 유사한 질문이 있었는지 검색해보세요. - 서로 예의를 지키며 존중하는 문화를 만들어가요. - 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요. 안녕하세요. 강의 너무 잘보구있습니다!!다름아니라 강의를 보던중 예외가 발생하면 throw new nest에서 제공되는 예외처리 이렇게 반환을 해주고있습니다. 그런데 제가 알고있는 부분으로는 throw시 그 함수가 즉시 중단되고 호출한 부분에서 try catch를 해줘야한다고 알고있었습니다. 그런데 강의에서도 그렇고 제가 직접해보았을때 그런 처리없이 postman으로 요청시 예외처리가 정상적으로 됩니다. 이게 어떤 흐름으로 되는것일까요?코드팩토리 통합 링크https://links.codefactory.aiFlutter 강의를 구매하시면 코드팩토리 디스코드 서버 플러터 프리미엄 채널에 들어오실 수 있습니다! 디스코드 서버에 들어오시고 저에게 메세지로 강의를 구매하신 이메일을 보내주시면 프리미엄 채널에 등록해드려요! 프리미엄 채널에 들어오시면 모든 질의응답 최우선으로 답변해드립니다!
-
해결됨[코드팩토리] [초급] NestJS REST API 백엔드 완전 정복 마스터 클래스 - Part 1 NestJS Core
프론트엔드에서 토큰을 받아왔을 때 어디에 저장해 두는 것이 좋은가요?
Access Token이나 Refresh Token을 서버에서 받아왔을 때 로컬 스토리지에 토큰들을 저장해 놓고 사용해도 괜찮은가요..?
-
미해결[코드팩토리] [초급] NestJS REST API 백엔드 완전 정복 마스터 클래스 - Part 1 NestJS Core
JwtStrategy 사용 vs 강의에서 말씀해주신 JwtService 만을 사용한 방법
- 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! - 먼저 유사한 질문이 있었는지 검색해보세요. - 서로 예의를 지키며 존중하는 문화를 만들어가요. - 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요.코드팩토리 통합 링크https://links.codefactory.aiFlutter 강의를 구매하시면 코드팩토리 디스코드 서버 플러터 프리미엄 채널에 들어오실 수 있습니다! 디스코드 서버에 들어오시고 저에게 메세지로 강의를 구매하신 이메일을 보내주시면 프리미엄 채널에 등록해드려요! 프리미엄 채널에 들어오시면 모든 질의응답 최우선으로 답변해드립니다! 안녕하세요 강사님. 좋은 강의를 만들어 주셔서 감사합니다. 다름이 아니라 JWT 인증에 대해서 궁금한 점이 있는데요 .강의에서는 JwtService 객체에서 제공해주는 함수를 활용하여 서비스 로직을 만든 후 이를 이용해 별도의 가드를 만들어 인증을 해주는 방식을 설명해주신걸로 이해했습니다. 그러나 인터넷 검색을 해봤을 떄 JwtStrategy 를 상속 받아서 local 전략과 token 전략을 구분하여 가드를 작성하고, 이를 사용하는 방식도 있는것으로 확인했습니다. 이 두가지 방법중에 서로의 장단점과 현업에서는 어떤 방식을 더 선호하는지 질문드립니다. 감사합니다.
-
미해결[코드팩토리] [초급] NestJS REST API 백엔드 완전 정복 마스터 클래스 - Part 1 NestJS Core
Refresh token 과 Access token 의 차이점
- 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! - 먼저 유사한 질문이 있었는지 검색해보세요. - 서로 예의를 지키며 존중하는 문화를 만들어가요. - 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요.코드팩토리 통합 링크https://links.codefactory.aiFlutter 강의를 구매하시면 코드팩토리 디스코드 서버 플러터 프리미엄 채널에 들어오실 수 있습니다! 디스코드 서버에 들어오시고 저에게 메세지로 강의를 구매하신 이메일을 보내주시면 프리미엄 채널에 등록해드려요! 프리미엄 채널에 들어오시면 모든 질의응답 최우선으로 답변해드립니다! 안녕하세요 강사님, Refresh token 과 Access token 의 차이 점은 아래 두개만 있는걸로 이해하면 될까요?만료 시간사용처 (access token 은 데이터 접근시, refresh token 은 access token 발급 시에 사용) 그 외에 인증 방식, payload data, 관리 방식은 모두 동일하다고 이해하면 될까요?
-
미해결[개정판 2023-11-27] Spring Boot 3.x 를 이용한 RESTful Web Services 개발
create posts 부분에서의 에러 발생
https://www.inflearn.com/course/lecture?courseSlug=spring-boot-restful-web-services&unitId=39127&tab=community&category=questionDetail&q=222413해당 강의에서의 posts create 부분에 500 interna error가 발생해서 문의드립니다 package com.example.restfulwebservice.bean; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; @Entity @Data @NoArgsConstructor @AllArgsConstructor public class Post { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String description; // 게시물:사용자는 N:1 관계 // JsonIgnore 통해서 정보를 가져오지 않음 @ManyToOne(fetch = FetchType.LAZY) // FetchType.LAZY는 지연 로딩, 사용자 데이터를 필요한 시점에 가져옴. 즉시 로딩 안함 @JsonIgnore // 다른 엄한 JsonIgnore를 불러오는 바람에 N+1 문제가 너무 크게 발생함.... private User user; } Post.java package com.example.restfulwebservice.Controller; import com.example.restfulwebservice.bean.Post; import com.example.restfulwebservice.bean.User; import com.example.restfulwebservice.exception.UserNotFoundException; import com.example.restfulwebservice.exception.UsersAndCountResponse; import com.example.restfulwebservice.repository.PostRepository; import com.example.restfulwebservice.repository.UserRepository; import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder; import org.springframework.http.ResponseEntity; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import javax.validation.Valid; import java.net.URI; import java.util.Date; import java.util.List; import java.util.Optional; import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn; @RestController @RequestMapping("/jpa") public class UserJPAController { private UserRepository userRepository; private PostRepository postRepository; public UserJPAController(UserRepository userRepository){ this.userRepository = userRepository; } // /jpa/users @GetMapping("/users") public List<User> retrieveAllUsers(){ return userRepository.findAll(); } // ResponseEntity를 사옹한 정답 코드 @GetMapping("/usersAndCount") public ResponseEntity retrieveAllUsersAndCount(){ List<User> users = userRepository.findAll(); int count = users.size(); UsersAndCountResponse result = UsersAndCountResponse.builder() .count(users.isEmpty() ? 0 : users.size()) .users(users) .build(); EntityModel entityModel = EntityModel.of(result); WebMvcLinkBuilder linkTo = linkTo(methodOn(this.getClass()).retrieveAllUsers()); entityModel.add(linkTo.withSelfRel()); return ResponseEntity.ok(entityModel); } // jpa/users/{id} @GetMapping("/users/{id}") public ResponseEntity retrieveUsersById(@PathVariable int id){ Optional<User> user = userRepository.findById(id); if (!user.isPresent()){ throw new UserNotFoundException("id - " + id); } EntityModel entityModel = EntityModel.of(user.get()); WebMvcLinkBuilder lintTo = linkTo(methodOn(this.getClass()).retrieveAllUsers()); entityModel.add(lintTo.withRel("all-users")); return ResponseEntity.ok(entityModel); } @DeleteMapping("/users/{id}") public void deleteUser(@PathVariable int id){ userRepository.deleteById(id); } // /jpa/users @PostMapping("/users") public ResponseEntity<User> createUser(@Valid @RequestBody User user){ if(user.getJoinDate() == null) user.setJoinDate(new Date()); User savedUser = userRepository.save(user); // USER CREATED // /users/4 // 생성된 User의 URI를 저장 후 반환하기 URI location = ServletUriComponentsBuilder .fromCurrentRequest() .path("/{id}") .buildAndExpand(savedUser.getId()) .toUri(); return ResponseEntity.created(location).build(); } @GetMapping("/users/{id}/posts") public List<Post> retrieveAllPostByUser(@PathVariable int id){ Optional<User> user = userRepository.findById(id); if(!user.isPresent()){ throw new UserNotFoundException("id-" + id + " user not found"); } return user.get().getPosts(); } @PostMapping("/users/{id}/posts") public ResponseEntity<Post> createPost(@PathVariable int id, @RequestBody Post post) { Optional<User> userOptional = userRepository.findById(id); if (!userOptional.isPresent()) { throw new UserNotFoundException("id-" + id); } User user = userOptional.get(); post.setUser(user); postRepository.save(post); URI location = ServletUriComponentsBuilder .fromCurrentRequest() .path("/{id}") .buildAndExpand(post.getId()) .toUri(); return ResponseEntity.created(location).build(); } } UserJPAController.java 파일이고, user의 post 통한 생성과 get 통한 id로 해당 사용자 post 조회는 이상 없습니다
-
미해결[C#과 유니티로 만드는 MMORPG 게임 개발 시리즈] Part6: 웹 서버
DB 설정 관련해서 질문 드립니다
[Table("UserTable")] public class UserData { [Key] public string UserId { get; set; } public string? Token { get; set; } [MaxLength(32)] public string? UserName { get; set; } public DateTime? CreateTime { get; set; } public BanData? Ban { get; set; } public ICollection<MailData> OwnMails { get; set; } public ICollection<GetMailData> GetMails { get; set; } } [Serializable] public class BanData { public DateTime Start { get; set; } public DateTime End { get; set; } public int State { get; set; } public string DescKey { get; set; } // Foreign Key public string UserId { get; set; } public UserData User { get; set; } } public class MailData { /// <summary> 우편물 구분 값 </summary> [Key] public long Id { get; set; } /// <summary> 발송일 </summary> public DateTime SendDate { get; set; } /// <summary> 우편물 받아야하는 기간 </summary> public DateTime EndDate { get; set; } /// <summary> 우편 내용물 </summary> public string Body { get; set; } /// <summary> 보낸이 ex)GM, DEV 등등 </summary> public string Sender { get; set; } // Foreign Key public string UserId { get; set; } public UserData User { get; set; } } /// <summary> 우편물 획득 시 </summary> public class GetMailData { /// <summary> 우편물 구분 값 </summary> [Key] public long Id { get; set; } /// <summary> 우편물 시간제한에 의한 삭제 </summary> public bool IsTimeOut { get; set; } /// <summary> 받은 날 </summary> public DateTime GetDate { get; set; } /// <summary> 우편 내용물 </summary> public string Body { get; set; } /// <summary> 보낸이 ex)GM, DEV 등등 </summary> public string Sender { get; set; } // Foreign Key public string UserId { get; set; } public UserData User { get; set; } }이렇게 SharedData.Models 정의를 해서 사용을 하고자 합니다 UserData에서만 DB 컬럼으로 활용을 하고싶습니다 ApplicationDbContext.csprotected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Ignore<BanData>(); modelBuilder.Ignore<MailData>(); modelBuilder.Ignore<GetMailData>(); }에는 DB로 만들어지지 않았으면 해서 예외처리를 추가했습니다 UserTableUserIdTokenUserNameCreateTimeBanData BanICollection<MailData> OwnMailsICollection<GetMailData> GetMails이런식으로 생성하게 하려면 어떻게해야 하나요?
-
미해결비전공자를 위한 풀스택 맛집지도 만들기 프로젝트!: Front, Back-end 그리고 배포까지
PM2 EADDRINUSE 에러
강의 보면서 PM2 배포를 따라해보았습니다. 5999번 포트를 사용했고, 몇 번 API 요청을 하면 EADDRINUSE 에러가 뜹니다. 0|index | Error: listen EADDRINUSE: address already in use :::5999 0|index | at Server.setupListenHandle [as listen2] (node:net:1872:16) 0|index | at listenInCluster (node:net:1920:12) 0|index | at Server.listen (node:net:2008:7) 0|index | at Function.listen (/home/ubuntu/hyerim-resume/server/nodemodules/express/lib/application.js:635:24) 0|index | at Object.<anonymous> (/home/ubuntu/hyerim-resume/server/index.js:6:11) 0|index | at Module._compile (node:internal/modules/cjs/loader:1376:14) 0|index | at Module._extensions..js (node:internal/modules/cjs/loader:1435:10) 0|index | at Module.load (node:internal/modules/cjs/loader:1207:32) 0|index | at Module._load (node:internal/modules/cjs/loader:1023:12) 0|index | at Object.<anonymous> (/home/ubuntu/.nvm/versions/node/v21.2.0/lib/node_modules/pm2/lib/ProcessContainerFork.js:33:23) { 0|index | code: 'EADDRINUSE', 0|index | errno: -98, 0|index | syscall: 'listen', 0|index | address: '::', 0|index | port: 5999 0|index | } 이 에러가 이미 사용중인 포트로 실행하려고 하는 문제라고 해서 매번 sudo lsof -i :5999, sudo kill -9 ~~ 로 서버를 껐다 키면 또 금방 해당 에러가 발생합니다. sudo lsof -i :5999 로 실행중인 프로세스를 확인하면 다음과 같습니다. COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME node\x20/ 1396 root 25u IPv6 451174 0t0 TCP ip-172-31-39-74.ap-northeast-2.compute.internal:5999->121.143.65.200:56521 (ESTABLISHED) node\x20/ 1396 root 26u IPv6 20785 0t0 TCP *:5999 (LISTEN) node\x20/ 1396 root 30u IPv6 451237 0t0 TCP ip-172-31-39-74.ap-northeast-2.compute.internal:5999->121.143.65.200:56645 (ESTABLISHED) Mac M2 로 서버에 접근해서 PM2를 실행하는데, Mac에서 AirPlay 모드를 꺼야 한다는 Stack Overflow 내용도 보고 꺼봤지만 역시나 에러가 뜹니다. pm2 start index.js —watch 로 pm2 인스턴스를 실행했더니 몇번 재시작을 자동으로 해주는 것 같지만 결국 재시작이 너무 잦다며 더이상 재시작이 되지 않는 것 같아요. 해결 방법이 궁금합니다 ㅠㅠ 아래는 제 서버의 package.json, index.js입니다. Package.json{ "name": "server", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "node index.js" }, "author": "", "license": "ISC", "dependencies": { "compression": "^1.7.4", "cors": "^2.8.5", "express": "^4.18.2", "jsonwebtoken": "^9.0.2", "method-override": "^3.0.0", "mysql2": "^3.6.3", "nodemon": "^3.0.1", "socket.io": "^4.7.2", "winston": "^3.11.0", "winston-daily-rotate-file": "^4.7.1" } } index.jsconst express = require("./config/express"); const { logger } = require("./config/winston"); //log const port = 5999; express().listen(port); logger.info(`API Server Start At Port ${port}`);
-
미해결[개정판 2023-11-27] Spring Boot 3.x 를 이용한 RESTful Web Services 개발
퀴즈 완료 후 질문드립니다
// UserAndCountResponse.java @AllArgsConstructor @ToString @Data public class UsersAndCountResponse { private int count; private List<User> users; } // UserJPAController.java @GetMapping("/usersAndCount") public UsersAndCountResponse retrieveAllUsersAndCount(){ List<User> users = userRepository.findAll(); int count = users.size(); System.out.println(new UsersAndCountResponse(count, users)); return new UsersAndCountResponse(count, users); } UserAndCountResponse.java 파일을 exception 혹은 response 폴더에 생성하여 다음과 같은 코드를 작성하였고, 406 error가 발생하였으나 @Data 어노테이션 추가하자 잘 동작했습니다 그런데 문제의 의도는 ResponseEntity 부분에 두 정보를 포함하는 것 같은데, 관련 키워드로 찾아봐도 복수의 응답을 포함하는 방법을 찾을 수 없었기에 질문드립니다
-
미해결[개정판 2023-11-27] Spring Boot 3.x 를 이용한 RESTful Web Services 개발
퀴즈 해설 질문드립니다
JPA를 이용한 사용자 추가와 삭제 - HTTP POST/DELETE method 강의의 과제 부분의 해설이나 정답지가 있으신가요?새로운 response를 생성하거나, 혹은 ResponseEntity에서 복수 정보를 반환하는 식으로 접근하려 하는데 맞는 접근 방법인지 모르겠습니다
-
미해결[개정판 2023-11-27] Spring Boot 3.x 를 이용한 RESTful Web Services 개발
yml파일에서 jpa설정을하고 에러가나요
Caused by: org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [boolean] for value [ture]이런 오류가나는데 뭐가 문제일까요?
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
상품수정 API 질문
상품 수정 api 질문합니다. 지금 보시면 update에는 async,await가 붙어있는데 데이터베이스를 거쳐 resolver로 가져오면 굳이 안붙어도 된다고 하셨는데 왜 붙어있는지 궁금합니다async update( {product,updateProductsService }:IProductsServiceUpdate):promise<Product> { const product=await this.findOne({productId}) this.checkSoldout({product}) }
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
조회 시, select로 일부 필드만 가져올 때 GraphQL 처리
안녕하세요 :)아래 코드와 같이 상품 조회할 때 select를 통해 일부 필드만 가져오도록 해봤습니다.service의 findAll 메서드에서는 유틸리티 타입으로 반환하도록 하였고,resolver에서는 Query 데코레이터에 GraphQL에서 제공하는 PickType으로 반환하게 했는데, 에러가 발생합니다.. (적절한 값이 아니라는 에러 내용)이런 상황에서는 메서드 반환 타입과 GraphQL 타입 처리를 어떻게 해주는 것이 좋은지 감이 잘 안 잡혀서 질문드려요! // products.resolver.ts @Query(() => [PickType(Product, ['id', 'name', 'description'])]) fetchProducts(): Promise<Pick<Product, 'id' | 'name' | 'description'>[]> { return this.productsService.findAll(); }// products.service.ts findAll(): Promise<Pick<Product, 'id' | 'name' | 'description'>[]> { return this.productsRepository.find({ select: ['id', 'name', 'description'], }); }
-
미해결비전공자를 위한 풀스택 맛집지도 만들기 프로젝트!: Front, Back-end 그리고 배포까지
인스턴스 중단 후 재시작
프로젝트를 완성하고 aws 인스턴스 프리티어 사용량이 제한량에 거의 도달해서 항상 켜놓으면 안되겠다고 생각해서 잠깐 중단시켰다가 며칠후에 재시작 시켰는데 재시작 한 이후로 지도상에 핀이 안 보이는데 어떻게 해야할까요? pm2도 해놔서 인스턴스를 중단했다가 재시작한것 때문인거 같은데... mysql을 접속하려 했을때 이런 창이 뜹니다.
-
해결됨[코드팩토리] [초급] NestJS REST API 백엔드 완전 정복 마스터 클래스 - Part 1 NestJS Core
섹션 26. 이미지 업로드 - 클래식 방법에서 질문이 있습니다!
안녕하세요!이미지 업로드 클래식 방법을 듣다 막히는 부분이 있어 질문 드립니다! @Post() @UseGuards(AccessTokenGuard) @UseInterceptors(FileInterceptor('image')) postPosts( @User('id') userId: number, @Body() body: CreatePostDto, @UploadedFile() file?: Express.Multer.File, console.log(userId); return this.postsService.createPost(userId, body, file?.filename); }컨트롤러에 해당 셋팅까지 마무리하고 postman으로 요청을 보내려고 시도를 했습니다. 하지만 400에러가 발생하더라고요 ㅠㅠ에러 message는 "Multipart : Malformed part header" 라고 표출이 됩니다. postman의 헤더 설정 문제인가해서 header셋팅하는 쪽 살펴보니 자동으로 header 설정이 되고 있어서 문제는 없는 것 같습니다.. 일단 컨트롤러에 요청자체가 걸리지 않는 것 같습니다ㅠ혹시 어떤 이유 일까요?