묻고 답해요
164만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
String cannot represent value 에러 여쭤봅니다!
강사님 파일 업로드 시에 파일은 정상적으로 다 업로드가 되는데 에러메시지가 계속 표시되서 여쭤봅니다!!
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
로드밸런서 관련 질문
안녕하세요.로드 밸런서 관련 질문드립니다.현재 구글 클라우드로 배포를 진행하며 하나의 인스턴스만 사용 중인데 로드밸런서로 어떻게 부하를 분산시켜줄 수 있나요?강의에서는 그냥 로드밸런서의 사용법을 학습하기 위해 큰 의미는 없지만 사용한 것인지 아니면 인스턴스가 하나라도 로드밸런서를 적용하면 좋은 점이 있는 것인지 궁금합니다.
-
미해결탄탄한 백엔드 NestJS, 기초부터 심화까지
자료를 공유폴더에 넣고 사용해도 데스크탑이랑 노트북이랑 둘다 잘될까요?
제목이 곧 질문입니다 수강생분들의 질문을 기다립니다! - 에러에 해당하는 질문은 "에러가 발생한 상황에 대한 충분한 설명", "에러 메세지", "에러가 난 코드 스크린샷"을 함께 첨부해주세요. - 언어에 해당하는 질문은 구글링 및 서치 후에 구체적으로 질문해주시면 좋습니다. - 간단한 진로 및 방향성에 대한 질문은 메일로 보내주세요.- 패키지 버전 관리은 실무 환경과 트랜드에 맞추어 강의를 업데이트 하고 있습니다. 강의를 그대로 따라갔는데 에러가 발생한다면 패키지 버전을 강의에서 사용하는 버전과 동일하게 맞춰주세요!- 강의 노트, QA 목록, 공지 사항을 먼저 확인해주세요.- 논리적이고 구체적인 질문은 학습 효과를 올립니다 :)
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
쿠키 세팅하고 return할때 질문이 있습니다.
import { Body, Controller, Post, Res } from '@nestjs/common'; import { AuthService } from './auth.service'; import { LoginUserValue } from './dto/cats.request.dto'; import { Response } from 'express'; @Controller('auth') export class AuthController { constructor(private readonly authService: AuthService) {} @Post() async login(@Body() val: LoginUserValue, @Res() res: Response) { const result = await this.authService.login(val); //cookie에 토큰을 담아서 보내줌 다음과 같이 console.log(result.refreshToken); console.log('여기서 못나가네'); res.setHeader( 'Set-Cookie', `refreshToken=${result.refreshToken}; path=/; `, ); console.log('뭐야 여기오네?'); // res.setHeader( // 'Set-Cookie', // `refreshToken=${result.refreshToken}; path=/; domain=localhost; SameSite=None; Secure; HttpOnly`, // ); // res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000'); res.json({ accesstoken: result.accessToken }); } } 먼저, 저는 지금 그래프큐엘을 사용하지않고restAPI를 사용하며 진도를 따라가고 있습니다.질문드릴 코드는 위와같이 되어있습니다. 원래는 return을 해주고있었는데 res설정하고 쿠키세팅하고나니까 return이 안먹고 클라이언트에서는 무한대기에 빠집니다. 그래서 혹시나해서 res.json으로 하니까 응답이 또 정상적으로 가더라구요..그래서 일단 다음과 같이 코드를 수정해두고 원래대로 return을 사용하고있는데혹시 정석은 어떻게 해야하는지 알려주시면 감사하겠습니다.임시 수정 코드import { Body, Controller, Post, Req, Res } from '@nestjs/common'; import { AuthService } from './auth.service'; import { LoginUserValue } from './dto/cats.request.dto'; import { Response } from 'express'; @Controller('auth') export class AuthController { constructor(private readonly authService: AuthService) {} @Post() async login( @Body() val: LoginUserValue, @Res({ passthrough: true }) res: Response, ): Promise<any> { const result = await this.authService.login(val); //cookie에 토큰을 담아서 보내줌 다음과 같이 res.setHeader( 'Set-Cookie', `refreshToken=${result.refreshToken}; path=/; `, ); // res.setHeader( // 'Set-Cookie', // `refreshToken=${result.refreshToken}; path=/; domain=localhost; SameSite=None; Secure; HttpOnly`, // ); // res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000'); return { accesstoken: result.accessToken }; } }
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
질문이있습니다.
현 시점에서 nest공식문서 가보면어센틱케이션에 passport는 없어지고그냥 @nestjs/jwt만 있는것으로 바뀌어있고passport는recipes카테고리로 이동되어있고install 도 $ npm install --save @nestjs/passport passport passport-local $ npm install --save-dev @types/passport-local이렇게 나와있는것으로 보이는데그냥 위 passport따라가면되나요?
-
해결됨Slack 클론 코딩[백엔드 with NestJS + TypeORM]
핫리로딩으로 공식문서와 동일하게 적용했는데 찾을 수 없다고만 뜨는데 이유가 뭘까요??
핫리로딩으로 공식문서와 동일하게 적용했는데 찾을 수 없다고만 뜨는데 이유가 뭘까요??아래 작성 코드 확인부탁드립니다! 터미널 에러PS C:\nestStudy\slack-clone-app\a-nest> npm run start:dev > a-nest@0.0.1 start:dev > nest build --webpack --webpackPath webpack-hmr.config.js --watch Error Cannot find module 'C:\nestStudy\slack-clone-app\a-nest\webpack-hmr.config.js' Require stack: - C:\nestStudy\slack-clone-app\a-nest\node_modules\@nestjs\cli\actions\build.action.js - C:\nestStudy\slack-clone-app\a-nest\node_modules\@nestjs\cli\actions\index.js - C:\nestStudy\slack-clone-app\a-nest\node_modules\@nestjs\cli\commands\command.loader.js - C:\nestStudy\slack-clone-app\a-nest\node_modules\@nestjs\cli\commands\index.js - C:\nestStudy\slack-clone-app\a-nest\node_modules\@nestjs\cli\bin\nest.js main.tsimport { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; declare const module: any; async function bootstrap() { const app = await NestFactory.create(AppModule); const port = process.env.PORT || 3000; await app.listen(3000); console.log(`listening on port ${port}`); if (module.hot) { module.hot.accept(); module.hot.dispose(() => app.close()); } } bootstrap(); webpack-hmr.config.jsconst nodeExternals = require('webpack-node-externals'); const { RunScriptWebpackPlugin } = require('run-script-webpack-plugin'); module.exports = function (options, webpack) { return { ...options, entry: ['webpack/hot/poll?100', options.entry], externals: [ nodeExternals({ allowlist: ['webpack/hot/poll?100'], }), ], plugins: [ ...options.plugins, new webpack.HotModuleReplacementPlugin(), new webpack.WatchIgnorePlugin({ paths: [/\.js$/, /\.d\.ts$/], }), new RunScriptWebpackPlugin({ name: options.output.filename, autoRestart: false }), ], }; }; package.json{ "name": "a-nest", "version": "0.0.1", "description": "", "author": "", "private": true, "license": "UNLICENSED", "scripts": { "build": "nest build", "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", "start": "nest start", "start:dev-backup": "nest start --watch", "start:dev": "nest build --webpack --webpackPath webpack-hmr.config.js --watch", "start:debug": "nest start --debug --watch", "start:prod": "node dist/main", "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", "test": "jest", "test:watch": "jest --watch", "test:cov": "jest --coverage", "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", "test:e2e": "jest --config ./test/jest-e2e.json" }, "dependencies": { "@nestjs/common": "^10.0.0", "@nestjs/core": "^10.0.0", "@nestjs/platform-express": "^10.0.0", "reflect-metadata": "^0.1.13", "rxjs": "^7.8.1" }, "devDependencies": { "@nestjs/cli": "^10.0.0", "@nestjs/schematics": "^10.0.0", "@nestjs/testing": "^10.0.0", "@types/express": "^4.17.17", "@types/jest": "^29.5.2", "@types/node": "^20.3.1", "@types/supertest": "^2.0.12", "@typescript-eslint/eslint-plugin": "^5.59.11", "@typescript-eslint/parser": "^5.59.11", "eslint": "^8.42.0", "eslint-config-prettier": "^8.8.0", "eslint-plugin-prettier": "^4.2.1", "jest": "^29.5.0", "prettier": "^2.8.8", "run-script-webpack-plugin": "^0.2.0", "source-map-support": "^0.5.21", "supertest": "^6.3.3", "ts-jest": "^29.1.0", "ts-loader": "^9.4.3", "ts-node": "^10.9.1", "tsconfig-paths": "^4.2.0", "typescript": "^5.1.3", "webpack": "^5.88.2", "webpack-node-externals": "^3.0.0" }, "jest": { "moduleFileExtensions": [ "js", "json", "ts" ], "rootDir": "src", "testRegex": ".*\\.spec\\.ts$", "transform": { "^.+\\.(t|j)s$": "ts-jest" }, "collectCoverageFrom": [ "**/*.(t|j)s" ], "coverageDirectory": "../coverage", "testEnvironment": "node" } }
-
미해결탄탄한 백엔드 NestJS, 기초부터 심화까지
스케마에서 리드온리로 버츄얼 작성할때 문의가있습니다.
id를 별도로 적어두질않으니 속성이 없다고 나오더라구요. 근데 선생님화면에서는 id가 없어도 에러가 안나던데 이유가 뭔가요? 일단 이렇게 id를 만들어두었더니 작동도 잘 되고 오류도 안나는데 선생님하고 다른점이 뭔지 궁금합니다.
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
비주얼스튜디오코드 폴더 복사 붙이기 문제
폴더 복사 붙여넣기 후 이름 변경시아래와 같은 에러가 뜬다면뭘 점검해 봐야 하나요?복사 붙이기로 새로 생성된 폴더 안의,파일을 열거나 하지 않았는데,복사 완료 후 폴더명 변경시 왜 오류가 나는 걸까요?답변 주시면 감사하겠습니다. Error: '03-04-rest-api-with-express-board-'을 (를) 'section03'(Error: EBUSY: resource busy or locked, rename 'c:\study\node_codecamp\class\section03\03-04-rest-api-with-express-board-' -> 'c:\study\node_codecamp\class\section03\03-04-rest-api-with-express-swagger')(으)로 이동할 수 없습니다.
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
섹션22 과제5번 질무이있습니다
아래 코드를 실행할때마다 오류가 발생해서 여쭤봤습니다. 그전에 startStandaloneServer가 없을때에는 오류는 안나왔지만 grapql페이지로 접속하였을때 빨간불이 들어오고 서버가 제대로 접속되지않아서 방법을 바꾸니 typeerror가 발생했는데 어디에서도 server.addPlugin을 작성하지않았고 공식페이지에서의 방법도 해봤는데 왜 오류가 나는지 찾지를 못했습니다import { ApolloServer } from "apollo-server"; import { startStandaloneServer } from "@apollo/server/standalone"; const typeDefs = `#test # Board에 관한 Query는 # 로직 내에 Query가 없는 채로 실행했을 때 나타나는 # "Error: Query root type must be provided." 에러 방지를 위한 것입니다. type BoardReturn { number: Int writer: String title: String contents: String } type Query { fetchBoards: [BoardReturn] } type Mutation { # 1. 아래에 createTokenOfPhone API의 요청 데이터 타입을 지정해 주세요. createTokenOfPhone(phone : Int) : String } `; const resolvers = { Query: { fetchBoards: (_, args) => { return [ { number: 1, writer: "철수", title: "제목입니다", contents: "내용입니다", }, { number: 2, writer: "영희", title: "좋은 날씨입니다", contents: "내용입니다", }, ]; }, }, Mutation: { createTokenOfPhone: (_, args) => { // 2. 아래 로직을 만들어 주세요. // (힌트: phone.js 내에 존재하는 함수들을 사용해서 로직을 완성해 주시면 됩니다. // 로직 구성이 어려우신 분들은 rest_api 폴더 내에 존재하는 index.js 파일을 참고해 주세요.) // 2-1. 휴대폰번호 자릿수 맞는지 확인하기 const phone = args.phone; if (phone.length > 10 || phone.length < 10) { return "핸드폰 번호 재확인 해주세요"; } // 2-2. 휴대폰 번호 자릿수가 맞다면 핸드폰 토큰 4자리 만들기 const result = String(Math.floor(Math.random() * 1000)).padStart(4, "0"); // 2-3. 만든 토큰을 핸드폰번호에 토큰 전송하기 return `token : ${result}`; }, }, }; const server = new ApolloServer({ typeDefs, resolvers, }); await startStandaloneServer(server); // server.listen(3000).then(({ url }) => { // console.log(`🚀 Server ready at ${url}`); // });
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
nodejs import 시 확장자 생략시 오류
//index.js import express from "express" const app = express() import { checkPhone } from "./phone.js" app.get("/", function (req, res) { res.send("Hello World") }) app.get("/phone", (req, res) => { const p = checkPhone() res.send(p) }) app.listen(3000) //phone.js export function checkPhone() { return true } 확장자를 생략해도 되는걸로 알고있었는데,확장자를 생략하면 왜 에러가 날까요?ERR_MODULE_NOT_FOUND에러가 나는 이유가 궁금합니다.
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
section22 의 CORS 관련 질문
안녕하세요!해당 수업에서 CORS 에러가 발생한 이유를 다른 작성자 분께서 질문해주셨는데, 강사님께서 프론트엔드와 백엔드의 포트가 달라서 그렇다고 대답해주셨습니다. 백엔드에서는 app.listen을 통해 포트를 설정을 해주었지만, 프론트엔드에서는 포트를 설정한 적이 없는데 포트번호를 어떻게 알 수 있나요..?설정하는 방법이 따로 있는건가요?그리고 이전수업에서 한 컴퓨터에서는 프론트엔드와 백엔드의 포트번호가 달라야한다고 말씀하셨는데, 그렇다면 하나의 컴퓨터에서는 same origin이 될 수 없는건가요?
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
파이썬이나 자바도 공부해야하나요?
이 강의만 들으면 되나요?아니면 파이썬이나 자바는 제가 따로 공부해야하나요?
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
버전 2으로 듣기
버전1으로 듣다가 버전2가 있다는 걸 알게 되어서 버전 1 말고 버전2으로 들어도 되나요?버전2는 처음부터 들으려고요
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
oauth 관련 질문 있어요.
안녕하세요. 강의 잘 듣고 있습니다.user - service - google가 있다고 했을 때,user가 oauth code grant방식으로 login을 하면 service가 callback을 통해 code를 받게되고, 그 정보와 다른 정보를 조합하여 google로 부터 access token과 refresh token을 받아올텐데요.여기서 token을 어떤식으로 처리하는지 궁금합니다.service가 google로 부터 받은 token들을 app으로 전달하는 건가요? 그렇다면 app은 token이 만료되면 google에 직접 토큰을 다시 요청하는걸까요? 아니면 service를 통해 relay를 해서 토큰을 다시 요청할까요? service는 token이 올바른건지는 검증할 수 없으니 db에 저장을 해 두고 나중에 같은 토큰을 user로부터 받았을때 같은지 비교해서 허용할 지 말지 알 수 있을거 같은데 이렇게 하는건가요?아니면 service가 직접 새로운 토큰들을 생성해서 관리하는게 좋을까요?그리고 public app에서 보안을 더 강화하기 위해 pkce방식도 쓰는거 같던데 실제 많이 쓰시는지 궁금하네요.답변 부탁드립니다.감사합니다.
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
ESLint 에러가 안나옵니다.
08-ESLint & Prettier 강의를 보는 중인데 5분 27초 경에 강의 에서 나오는 eslint 에러가 저는 안나옵니다. eslint가 적용이 안되고 있는걸까요?강의 화면제 vscode 화면
-
해결됨탄탄한 백엔드 NestJS, 기초부터 심화까지
[질문X] websockets 설치 불가 이슈 공유
TLDRNestJS를 최신 버전으로 업그레이드하여 프로젝트를 다시 생성하시면 설치가 가능합니다.Details2023년 6월 15일 기준 NestJS의 v10 릴리즈가 나와, 이전 버전의 CLI로 설치된 경우 아래 명령어 실행 시 에러가 발생합니다. (작성자의 경우 NestJS v9로 실행)$ npm i --save @nestjs/websockets @nestjs/platform-socket.io npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: test-chat@0.0.1 npm ERR! Found: @nestjs/common@9.4.3 npm ERR! node_modules/@nestjs/common npm ERR! @nestjs/common@"^9.0.0" from the root project npm ERR! npm ERR! Could not resolve dependency: npm ERR! peer @nestjs/common@"^10.0.0" from @nestjs/websockets@10.1.0 npm ERR! node_modules/@nestjs/websockets npm ERR! @nestjs/websockets@"*" from the root project npm ERR! npm ERR! Fix the upstream dependency conflict, or retry npm ERR! this command with --force or --legacy-peer-deps npm ERR! to accept an incorrect (and potentially broken) dependency resolution.이를 해결하기 위한 방법으로 두 가지를 생각해볼 수 있는데, 작성자 본인은 첫 번째 방법을 사용했음을 알려드립니다.NestJS v10으로 새로 설치 후 프로젝트 다시 생성공식문서(링크)를 따라 v9에서 v10으로 마이그레이션
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
QueryFailedError: Table 'user' already exists
안녕하세요 선생님 다름이 아니라 synchronize: true, // 동기화 시켜준다 같게 한다.true을 하게되면 동기화를 시켜주는건데 매번 yarn start:dev을할때마다 QueryFailedError: Table '***' already exists이러한 오류가 나옵니다. 그럼 실행 할때마다 데이터베이스 테이블을 매번 지워야 하는건가요??
-
미해결지금 당장 NestJS 백엔드 개발 [사주 만세력]
회원가입 음력 날짜
회원가입시 음력으로 가입시도를 자꾸 실패해서 살펴보니 데이터베이스에 음력 날짜(lunarDate)가 9999-12-31 로 동일하던데 음력 데이터가 입력 날짜와 같은 값이 없어서 가입이 안되는 거죠? 음력 데이터는 없는건가요?
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
swaggerui에서 execute했는데 console에서는 계속 typeerror로 n.get함수가 없다는 에러가 발생합니다.
javascript문서를 확인했을때는 배열을 객체로쓴다던가 함수를 부를수없는곳에 작성했다는등의 오류라고 나와있는데 아무리 찾아봐도 그오류가 어디에서 나오는지 왜나오는지를 알수없어서 질문올립니다.// index.jsimport express from "express"; import { options, dataCoffee, dataUsers } from "./swagger/config.js"; import cors from "cors"; const app = express(); import swaggerUi from "swagger-ui-express"; import swaggerJSDoc from "swagger-jsdoc"; app.use(express.json()); const swaggerSpec = swaggerJSDoc(options); app.use(cors()); app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerSpec)); app.get("/users", (req, res) => { res.send(dataUsers); }); app.get("/starbucks", function (req, res) { res.send(dataCoffee); }); app.listen(3001); // config.jsexport const options = { definition: { openapi: "3.0.0", info: { title: "swagger-test", version: "1.0.0", }, }, apis: ["./swagger/*-swagger.js"], // files containing annotations as above }; export const dataCoffee = [ { name: "아메리카노", kcal: 5 }, { name: "카푸치노", kcal: 125 }, { name: "헤이즐넛", kcal: 85 }, { name: "카라멜마키아또", kcal: 225 }, { name: "휘핑크림추가", kcal: 115 }, { name: "아메리카노", kcal: 5 }, { name: "아메리카노", kcal: 5 }, { name: "아메리카노", kcal: 5 }, { name: "아메리카노", kcal: 5 }, { name: "아메리카노", kcal: 5 }, { name: "아메리카노", kcal: 5 }, { name: "아메리카노", kcal: 5 }, { name: "아메리카노", kcal: 5 }, { name: "아메리카노", kcal: 5 }, ]; export const dataUsers = [ { email: "aaa@gmail.com", name: "짱구", phone: "010-2293-3333", personal: "222012-2210392", prefer: "https://google.com", }, { email: "aaa@gmail.com", name: "짱구2", phone: "010-2293-3333", personal: "222012-2210392", prefer: "https://google.com", }, { email: "aaa@gmail.com", name: "짱구3", phone: "010-2293-3333", personal: "222012-2210392", prefer: "https://google.com", }, { email: "aaa@gmail.com", name: "짱구4", phone: "010-2293-3333", personal: "222012-2210392", prefer: "https://google.com", }, { email: "aaa@gmail.com", name: "짱구5", phone: "010-2293-3333", personal: "222012-2210392", prefer: "https://google.com", }, { email: "aaa@gmail.com", name: "짱구6", phone: "010-2293-3333", personal: "222012-2210392", prefer: "https://google.com", }, ];// all-swagger.js/** * @swagger * /starbucks: * get: * summary: 커피 * tags: [Coffee] * parameters: * name: String * kcal: int * responses: * 200: * description: 성공 * content: * application/json: * schema: * type: array * items: * properties: * name: * type: String * example: 아메리카노 * kcal: * type: int * example: 5 */ /** * @swagger * /users: * get: * summary: 유저검색 * tags: [Users] * parameters: * name: String * kcal: int * responses: * 200: * description: 성공 * content: * application/json: * schema: * type: array * items: * properties: * name: * type: String * example: 아메리카노 * kcal: * type: int * example: 5 */
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
[세션30] fetchUser시 UseGuard 401에러
안녕하세요, jwt토큰을 입력하여 사용자 인가를 받고 싶은데 그 과정에서 계속 오류가 나서 문의드립니다. 제가 확인하기로는 코드도 정확히 입력하고, HTTP HEADERS로 보내주는 토큰도 문제 없어서요. 에러 강의에서 jwt를 넣어주지 않았을 때 발생한다는 에러가 발생합니다. 제가 보기에는 토큰값이 잘못된것 같은데, login으로 받아온 토큰을 바로 넣는거라 만료가 되지도 않았을텐데 해결이 안되네요. 제 코드는 아래와 같습니다. users.resolver.ts// users.resolver.ts import { Args, Int, Mutation, Query, Resolver } from '@nestjs/graphql'; import { User } from './entities/user.entity'; import { UsersService } from './users.service'; import * as bcrypt from 'bcrypt'; import { UseGuards } from '@nestjs/common'; import { GqlAuthAccessGuard } from '../auth/guards/gql-auth.guard'; // import { AuthGuard } from '@nestjs/passport'; // 추가 @Resolver() export class UsersResolver { constructor( private readonly usersService: UsersService, // ) {} @UseGuards(GqlAuthAccessGuard) // 수정 @Query(() => String) fetchUser(): string { console.log('인가에 성공하였습니다'); return '인가에 성공하였습니다.'; } @Mutation(() => User) async createUser( @Args('email') email: string, @Args('password') password: string, @Args('name') name: string, @Args({ name: 'age', type: () => Int }) age: number, ): Promise<User> { // const hashedPassword = await bcrypt.hash(password, 10); // return this.usersService.create({ email, hashedPassword, name, age }); // } return this.usersService.create({ email, password, name, age }); } } gql-auth.guard.ts import { ExecutionContext } from '@nestjs/common'; import { GqlExecutionContext } from '@nestjs/graphql'; import { AuthGuard } from '@nestjs/passport'; export class GqlAuthAccessGuard extends AuthGuard('access') { getRequest(context: ExecutionContext) { const gqlContext = GqlExecutionContext.create(context); return gqlContext.getContext().req; } } jwt-access.strategy.ts import { PassportStrategy } from '@nestjs/passport'; import { ExtractJwt, Strategy } from 'passport-jwt'; export class JwtAccessStrategy extends PassportStrategy(Strategy, 'access') { constructor() { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), secretOrKey: '나의비밀번호', }); } validate(payload) { console.log('페이로드', payload); return { id: payload.sub, }; } } auth.module.tsimport { Module } from '@nestjs/common'; import { AuthResolver } from './auth.resolver'; import { AuthService } from './auth.service'; import { UsersModule } from '../users/users.module'; import { JwtModule } from '@nestjs/jwt'; import { JwtAccessStrategy } from './strategy/jwt-access.strategy'; @Module({ imports: [ JwtModule.register({}), UsersModule, // 서비스를 각각 불러오기보다는 module을 통으로 불러오는게 낫다. 원래는 import 에 TypeOrmModule.forFeature([Users])& providers에 UsersServie가 있었음. ], providers: [ JwtAccessStrategy, AuthResolver, // AuthService, // ], }) export class AuthModule {}