172만명의 커뮤니티!! 함께 토론해봐요.
미해결
Next + React Query로 SNS 서비스 만들기
const onClickClose = () => { router.back(); modalStore.reset(); }; 뒷 부분에 기능을 추가하실지는 모르겠지만 현재 onClickClose를 하고나서 모달을 reset 해줘야 할 것 같습니다. 아니면 계속 상태를 가지고 있어서 나가고 나서도 reset이 이뤄져야 할 것 같습니다!
react next.js react-query next-auth msw
이종민
2024-01-08T08:52:43.446Z
댓글 1
좋아요 2
조회수 410
미해결
실전! 스프링 부트와 JPA 활용2 - API 개발과 성능 최적화
학습하는 분들께 도움이 되고, 더 좋은 답변을 드릴 수 있도록 질문전에 다음을 꼭 확인해주세요. 1. 강의 내용과 관련된 질문을 남겨주세요. 2. 인프런의 질문 게시판과 자주 하는 질문(링크)을 먼저 확인해주세요. (자주 하는 질문 링크: https://bit.ly/3fX6ygx) 3. 질문 잘하기 메뉴얼(링크)을 먼저 읽어주세요. (질문 잘하기 메뉴얼 링크: https://bit.ly/2UfeqCG) 질문 시에는 위 내용은 삭제하고 다음 내용을 남겨주세요. ========================================= [질문 템플릿] 1. 강의 내용과 관련된 질문인가요? (예/아니오) 2. 인프런의 질문 게시판과 자주 하는 질문에 없는 내용인가요? (예/아니오) 3. 질문 잘하기 메뉴얼을 읽어보셨나요? (예/아니오) [질문 내용] 여기에 질문 내용을 남겨주세요. 영한쌤이 말씀해주신 Controller -> Application Service -> Domain Service -> Repository에서 Application Service: 트랜잭션의 시작, Domian Service에 있는 순수 도메인 로직들을 활용하여, 복잡한 애플리케이션 비즈니스 로직을 구성 Domain Service : 도메인에 대한 순수한 로직으로 구성. Application Service의 도구로서 활용됨. OSIV를 off 상태이기 때문에 Controller에 반환시 Application Service에서는 응답 Dto로 넘겨줘야 하는데 여기서 한가지 고민이 있습니다. 아키텍쳐는 위에서 아래로 순방향으로 흘러야 하는데 (역행, 순환 참초 X). Application Service에서 Controller단에 종속적인 응답 Dto를 넘기게 된다면, Application Service와 Controller간에 순환 참조와 역류 참조가 일어나지 않아 문제이지 않나 싶습니다... 상관이 없는지 아니면 어떻게 해결해야 좋을까요?
두잇베스트
2024-01-08T07:57:53.183Z
댓글 1
좋아요 0
조회수 429
미해결
[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
강의 4:50 정도에 아래 코드에서 x를 콘솔에 출력하면 undefined가 발생한다고 하셨는데 이해가 안가서 질문드립니다. const sum = function(){ var x = 0; } console.log(x); var로 선언된 x는 콘솔이 찍히는 부분인 현재 스코프에서 사용할 수 없는 상태이므로 undefined가 아니라 referenceError가 나는거 아닌가요?
react node.js seo graphql next.js
yewon921
2024-01-08T07:47:48.341Z
댓글 1
좋아요 0
조회수 191
해결됨
[리뉴얼] React로 NodeBird SNS 만들기
안녕하세요 선생님 상황)req.logout안에 콜백 함수넣어서 로그아웃이 잘 되고 있었는데, isLoggedIn추가 후 상태코드 401이 뜨고 preview에는 로그인이 필요합니다가 뜨며 로그아웃 안되는 상황입니다. network 로그인 했을 때 로그아웃 했을 때 network 로그아웃 했을 때 preview redux 로그인 했을 때 로그아웃 했을 때 시도해본것) 로그인 후 세션정보 콘솔 출력 router.post('/login', isNotLoggedIn, (req, res, next)=> { passport.authenticate('local',(err, user, info) => { if(err) { console.error(err); return next(err); } if(info) { return res.status(401).send(info.reason); } return req.login(user,async(loginErr)=> { if(loginErr) { console.error(loginErr); return next(loginErr); } console.log('로그인 후 세션 정보:', req.session); //생략 }); })(req, res, next); }); //POST /user/login user.js의 logout에서 에러 발생시 출력 => 출력 x router.post('/logout', isLoggedIn, (req, res) => { req.logout((err) => { if (err) { console.error(err); return res.status(500).send('로그아웃 중 오류가 발생했습니다.'); } res.send('ok'); req.session.destroy(); }); }); Middlewares에서 req.isAuthenticated()확인 => 결과 false exports.isLoggedIn = (req, res, next) => { console.log('로그인 상태 확인:', req.isAuthenticated()); if(req.isAuthenticated()) { next(); } else { res.status(401).send('로그인이 필요합니다.'); } } 질문)req.isAuthenticated가 false로 나와서 로그아웃이 안되는데 원인과 해결방법이 궁금합니다. 혹시 로그인하면 이것을 true가 되게 바꾸는 방법이 있나요? req.isAuthenticated() 작성한 코드) UserProfile import React, {useCallback} from 'react'; import {useDispatch, useSelector} from 'react-redux'; import {Card, Avatar, Button} from 'antd'; import styled from 'styled-components'; import {logoutRequestAction} from '../reducers/user'; const ButtonWrapper = styled(Button)` display: block; margin-left: auto; margin-right: auto; ` const UserProfile = () => { const dispatch = useDispatch(); const { me, logOutLoading } = useSelector((state) => state.user); const onLogout = useCallback(()=>{ dispatch(logoutRequestAction()); }, []); return ( //생략 <ButtonWrapper onClick={onLogout} loading={logOutLoading}>로그아웃</ButtonWrapper> ); } export default UserProfile; reducers/user import {produce} from 'immer'; export const initialState = { logOutLoading: false,//logout시도중 logOutDone: false, logOutError: null, } export const LOG_OUT_REQUEST = 'LOG_OUT_REQUEST'; export const LOG_OUT_SUCCESS = 'LOG_OUT_SUCCESS'; export const LOG_OUT_FAILURE = 'LOG_OUT_FAILURE'; export const logoutRequestAction = () => { return { type: LOG_OUT_REQUEST } } const reducer = (state = initialState, action) => produce(state, (draft) => { switch(action.type){ case LOG_OUT_REQUEST: draft.logOutLoading = true; draft.logOutDone = false; draft.logOutError = null; break; case LOG_OUT_SUCCESS: draft.logOutLoading = false; draft.logOutDone = true; draft.me = null; break; case LOG_OUT_FAILURE: draft.logOutLoading = false; draft.logOutError = action.error; break; default: break; } }); export default reducer; sagas/user import axios from 'axios'; import { all, call, delay, fork, put, takeLatest } from 'redux-saga/effects'; import { LOG_OUT_FAILURE, LOG_OUT_REQUEST, LOG_OUT_SUCCESS, } from '../reducers/user'; function logOutAPI(){ return axios.post('/user/logout'); } function* logOut() { try{ yield call(logOutAPI); yield put({ type: LOG_OUT_SUCCESS, }); } catch(err) { yield put({ type: LOG_OUT_FAILURE, error: err.response.data }); } } function* watchLogOut(){ yield takeLatest(LOG_OUT_REQUEST, logOut); } export default function* userSaga() { yield all ([ fork(watchLogOut), ]) } routes/user.js const express = require('express'); const bcrypt = require('bcrypt'); const {User, Post} = require('../models'); const router = express.Router(); const passport = require('passport'); const {isLoggedIn, isNotLoggedIn} = require('./middlewares'); router.post('/login', isNotLoggedIn, (req, res, next)=> { passport.authenticate('local',(err, user, info) => { if(err) { console.error(err); return next(err); } if(info) { return res.status(401).send(info.reason); } return req.login(user,async(loginErr)=> { if(loginErr) { console.error(loginErr); return next(loginErr); } const fullUserWithoutPassword = await User.findOne({ where: {id: user.id}, attributes:{ exclude:['password'] }, include: [{ model: Post }, { model: User, as:'Followings', }, { model: User, as:'Followers' }] }) return res.status(200).json(fullUserWithoutPassword); }); })(req, res, next); }); //POST /user/login //생략 const {isLoggedIn, isNotLoggedIn} = require('./middlewares'); router.post('/logout', isLoggedIn, (req, res) => { req.logout(() => { req.session.destroy(); res.send('ok'); }); }); routes/middlewares exports.isLoggedIn = (req, res, next) => { if(req.isAuthenticated()) { next(); } else { res.status(401).send('로그인이 필요합니다.'); } } exports.isNotLoggedIn = (req, res, next) => { if(!req.isAuthenticated()){ next(); } else { res.status(401).send('로그인 하지 않은 사용자만 접근이 가능합니다.'); } } passport/index const passport = require('passport'); const local = require('./local'); const { User } = require('../models'); module.exports = () => { passport.serializeUser((user,done) => { done(null,user.id);//첫번째 인자 에러, 두번째 인자 성공(쿠키와 묶어줄 user아이디만 저장) }); passport.deserializeUser(async(id, done) => { try { const user = await User.findOne({where:{id}}) done(null,user); } catch(error) { console.error(error); done(error); } }); local(); }; passport/local const passport = require('passport'); const {Strategy:LocalStrategy} = require('passport-local'); const bcrypt = require('bcrypt'); const {User} = require('../models'); const express = require('express'); const router = express.Router(); router.post('/login', passport.authenticate('local')); module.exports = () => { passport.use(new LocalStrategy({ usernameField: 'email', passwordField: 'password', }, async(email, password, done) => { try { const user = await User.findOne({ where:{email} }); if(!user) { return done(null, false, {reasone: '존재하지 않는 이메일입니다!'}) } const result = await bcrypt.compare(password, user.password); if(result) { return done(null, user);//성공에 사용자 정보 넘겨줌 } return done(null, false, {reason:'비밀번호가 틀렸습니다.'}); } catch(error) { return done(error); } })); } 사용 하는 OS )mac 설치 버전) back { "name": "react-nodebird-back", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "luckyhaejin", "license": "ISC", "dependencies": { "bcrypt": "^5.1.1", "cookie-parser": "^1.4.6", "cors": "^2.8.5", "dotenv": "^16.3.1", "express": "^4.18.2", "express-session": "^1.17.3", "mysql2": "^3.6.5", "passport": "^0.7.0", "passport-local": "^1.0.0", "sequelize": "^6.35.2", "sequelize-cli": "^6.6.2" }, "devDependencies": { "nodemon": "^2.0.22" } }
react redux node.js express next.js
박해진
2024-01-08T06:19:12.374Z
댓글 2
좋아요 0
조회수 441
해결됨
Next.js 필수 개발 가이드 3시간 완성!
제목 : auth 해보고 있는데 오류가 나오고있네용 설명 : 저는 prisma를 postgresql로 하고있습니다. 그래도 왜 이런 오류가 나오는지 원인은 잘 모르겠네요 내용: auth에서 credentials를 하고 있습니다. import NextAuth from "next-auth"; import CredentialsProvider from "next-auth/providers/credentials"; import KakaoProvider from "next-auth/providers/kakao"; import NaverProvider from "next-auth/providers/naver"; import { PrismaAdapter } from "@auth/prisma-adapter"; import prisma from "@root/src/server/prisma"; import bcrypt from "bcrypt"; export const authOptions = { providers: [ CredentialsProvider({ name: "Credentials", credentials: { accountId: { label: "Username", type: "text" }, password: { label: "Password", type: "password" }, email: { label: "Email", type: "email" }, name: { label: "Name", type: "text" }, }, async authorize(credentials, req) { if (!credentials?.email || !credentials.password) { return null; } const exUser = prisma.user.findUnique({ where: { accountId: credentials.accountId as string, email: credentials.email as string, password: credentials.password, name: credentials.name as string, }, }); if (!exUser) return null; const passwordMatch = await bcrypt.compare( credentials.password as string, exUser.password! // 오류 발생 ); return passwordMatch ? exUser : null; }, }), KakaoProvider({ clientId: process.env.KAKAO_CLIENT_ID!, clientSecret: process.env.KAKAO_CLIENT_SECRET!, }), NaverProvider({ clientId: process.env.NAVER_CLIENT_ID!, clientSecret: process.env.NAVER_CLIENT_SECRET!, }), ], adapter: PrismaAdapter(prisma), }; const handler = NextAuth(authOptions); // authOptions 오류 발생 export { handler as GET, handler as POST }; 이건 제 소스이고, authOptions와 exUser.password! 부분에서 에러가 나오고 있는데 원인을 잘 모르겠습니다. 해당 오류입니다. 'Prisma__UserClient<{ id: string; accountId: string | null; name: string | null; email: string | null; emailVerified: Date | null; image: string | null; phone: string; password: string; role: ROLE; } | null, null, DefaultArgs>' 형식에 'password' 속성이 없습니다.ts(2339) 아래는 authOptions 오류입니다. '{ providers: (CredentialsConfig<Record<string, CredentialInput>> | OAuthConfig<KakaoProfile> | OAuthConfig<...>)[]; adapter: Adapter; }' 형식의 인수는 'NextAuthConfig' 형식의 매개 변수에 할당될 수 없습니다. 'adapter.linkAccount'의 형식은 해당 형식 간에 호환되지 않습니다. '((account: import("/Users/hwangjeong-yeon/workspace/Project/FOCC/focc/node_modules/@auth/core/adapters").AdapterAccount) => Promise<void> | import("/Users/hwangjeong-yeon/workspace/Project/FOCC/focc/node_modules/@auth/core/types").Awaitable<import("/Users/hwangjeong-yeon/workspace/Project/FOCC/focc/node_modules/@aut...' 형식은 '((account: import("/Users/hwangjeong-yeon/workspace/Project/FOCC/focc/node_modules/next-auth/node_modules/@auth/core/adapters").AdapterAccount) => Promise<void> | import("/Users/hwangjeong-yeon/workspace/Project/FOCC/focc/node_modules/next-auth/node_modules/@auth/core/types").Awaitable<...>) | undefined' 형식에 할당할 수 없습니다. '(account: import("/Users/hwangjeong-yeon/workspace/Project/FOCC/focc/node_modules/@auth/core/adapters").AdapterAccount) => Promise<void> | import("/Users/hwangjeong-yeon/workspace/Project/FOCC/focc/node_modules/@auth/core/types").Awaitable<import("/Users/hwangjeong-yeon/workspace/Project/FOCC/focc/node_modules/@auth...' 형식은 '(account: import("/Users/hwangjeong-yeon/workspace/Project/FOCC/focc/node_modules/next-auth/node_modules/@auth/core/adapters").AdapterAccount) => Promise<void> | import("/Users/hwangjeong-yeon/workspace/Project/FOCC/focc/node_modules/next-auth/node_modules/@auth/core/types").Awaitable<...>' 형식에 할당할 수 없습니다. 'Promise<void> | import("/Users/hwangjeong-yeon/workspace/Project/FOCC/focc/node_modules/@auth/core/types").Awaitable<import("/Users/hwangjeong-yeon/workspace/Project/FOCC/focc/node_modules/@auth/core/adapters").AdapterAccount | null | undefined>' 형식은 'Promise<void> | import("/Users/hwangjeong-yeon/workspace/Project/FOCC/focc/node_modules/next-auth/node_modules/@auth/core/types").Awaitable<import("/Users/hwangjeong-yeon/workspace/Project/FOCC/focc/node_modules/next-auth/node_modules/@auth/core/adapters").AdapterAccount | null | undefined>' 형식에 할당할 수 없습니다. 'AdapterAccount' 형식은 'Promise<void> | Awaitable<AdapterAccount | null | undefined>' 형식에 할당할 수 없습니다. 'AdapterAccount' 형식에 'Promise<void>' 형식의 then, catch, finally, [Symbol.toStringTag] 속성이 없습니다.ts(2345) const authOptions: { providers: (CredentialsConfig<Record<string, CredentialInput>> | OAuthConfig<KakaoProfile> | OAuthConfig<...>)[]; adapter: Adapter; } 혹시 제가 schema 부분에서 오류가 있을까요? model User { id String @id @default(cuid()) accountId String? name String? email String? @unique emailVerified DateTime? image String? phone String @default("") password String @default("") role ROLE @default(USER) accounts Account[] sessions Session[]
황정연
2024-01-08T06:00:50.361Z
댓글 2
좋아요 1
조회수 623
해결됨
[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
오류가 나옵니다 new:1 Access to fetch at 'http://backend-practice.codebootcamp.co.kr/graphql' from origin 'http://localhost:3002' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'http://localhost:3000' that is not equal to the supplied origin. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. backend-practice.codebootcamp.co.kr/graphql:1 Failed to load resource: net::ERR_FAILED
react node.js seo graphql next.js
comjjang2
2024-01-08T05:57:37.626Z
댓글 1
좋아요 0
조회수 220
미해결
실전! 스프링 부트와 JPA 활용1 - 웹 애플리케이션 개발
현재 실전 스프링부트와 jpa활용1편을 수강중입니다. 엔티티 클래스 개발2 에서 카테고리 클래스를 만들 때, 부모 객체는 왜 생성하는지 이해가 되지 않습니다..! 이미 카테고리 클래스 자체가 부모 클래스가 되는게 아닌가요..?
java spring 웹앱 spring-boot jpa
ㅎㅅㅎ
2024-01-08T05:50:46.126Z
댓글 1
좋아요 0
조회수 438
미해결
Next + React Query로 SNS 서비스 만들기
11분대에서 선생님께서 진행하신 코드 부분에서 질문이 있습니다.session 정보를 부모 컴포넌트로부터 받아오는 방식과 useSession()을 통해 받아오는 방식에는 어떤 차이점이 존재하나요?? 서버에서 prerendering할 때, 미리 렌더링이 잘되도록 하기 위함인가요?
react next.js react-query next-auth msw
이종민
2024-01-08T05:36:53.122Z
댓글 1
좋아요 0
조회수 514
미해결
[리뉴얼] React로 NodeBird SNS 만들기
안녕하세요 선생님 상황) 백엔드 서버 실행시 인덱스를 64개까지 만들 수 있다는 에러가 발생했습니다. 시도해본 것) 인덱스 삭제 명령어를 찾아보았는데 인덱스 명을 붙여줘야해서 한개씩 지울 수 있는 상황입니다. alter table `Users` drop index `email_15` 질문) 혹시 Users테이블에 email 컬럼에 대한 인덱스 전체를 한번에 지울 수 있는 방법이 있을까요?
react redux node.js express next.js
박해진
2024-01-08T05:01:12.333Z
댓글 2
좋아요 0
조회수 476
미해결
Next + React Query로 SNS 서비스 만들기
export default function Page({ params }: { params: { postId: number } }){ } 다음과 같이 app/(Logined)/home/Post/[postId]/page.tsx 에서 params를 불러왔을 때, prisma와 REST API를 이용하여 데이터를 요청하고 가져오는 것을 할 때, 1.page가 params.postId를 이용하여 NextRequest를 요청하면 2. route.ts가 해당 Request를 받고 prisma를 통해 쿼리를 한 뒤, 3. NextResponse로 page에 답장하는 형식을 구현하고자 합니다. 근데 해당 구현에 대해서, 공식 문서에서 제가 해당 내용을 잘 응용하지 못하는 것인지, GET http://localhost:3000/api/post/4 500 (Internal Server Error)에러만 발생하고 'post'를 불러오지 못하고 있습니다. 이에 눈에 띄는 코드 오류는 없는지 핵심 부분이 빠진 것은 없는지 질문 드립니다. // app/(Logined)/home/Post/[postId]/page.tsx "use client"; import React, { useEffect, useState } from "react"; import { PostType } from "@/app/(Logined)/_components/TYPE_post"; export default function Page({ params }: { params: { postId: number } }) { const [post, setPost] = useState<PostType | null>(null); const postid = params.postId; useEffect(() => { const fetchPostData = async () => { try { const response = await fetch(`/api/post/${postid}`); if (response.ok) { const postData: PostType = await response.json(); setPost(postData); } else { console.error("Error fetching post"); } } catch (error) { console.error("Error:", error); } }; if (params.postId) { fetchPostData(); } }, [params.postId]); if (!post) { return <div>Loading...</div>; } return ( <div> <h1>Post Details</h1> <p>Description: {post.description}</p> <p>Event Date: {post.eventDate.toString()}</p> <p>Deadline: {post.deadline.toString()}</p> </div> ); } // pages/api/post/[postId]/route.ts import prisma from "@/app/lib/prisma"; import { NextResponse, NextRequest } from "next/server"; export async function GET(req: NextRequest) { const postId = parseInt(req.nextUrl.searchParams.get("postId") || "0"); if (!postId) { return new NextResponse(JSON.stringify({ message: "Invalid post ID" }), { status: 400, }); } try { const post = await prisma.post.findUnique({ where: { id: postId }, select: { description: true, eventDate: true, deadline: true, }, }); if (post) { return new NextResponse(JSON.stringify(post)); } else { return new NextResponse(JSON.stringify({ message: "Post not found" }), { status: 404, }); } } catch (error) { console.error("Error fetching post:", error); return new NextResponse( JSON.stringify({ message: "Error fetching post" }), { status: 500 } ); } }
이석희
2024-01-07T16:29:56.656Z
댓글 1
좋아요 0
조회수 205
미해결
Next + React Query로 SNS 서비스 만들기
선생님께서 무한 스크롤 설명해주실 때의 예시처럼 현재 게시물이 [[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15]] 이렇게 있다고 쳤을 때, unshift를 통해 게시물을 넣게 된다면 [[16, 1, 2, 3, 4,5], [6, 7, 8, 9, 10], [11,12,13,14,15]] 이렇게 된다면 2차원 배열의 첫 번째 배열의 원소가 6개가 되는데, 이렇게 되면 마지막 배열개수가 6개보다 적어 스크롤을 내려도 게시물을 안가져오는 상황은 이뤄지지 않는 건가요?
react next.js react-query next-auth msw
이종민
2024-01-07T14:54:35.929Z
댓글 2
좋아요 0
조회수 470
해결됨
[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
기존 노트북에서는 잘 되었다가 다른 노트북에서 깃허브에서 pull해서 설정잡고 실행시키니 404에러가 뜹니다. yarn dev시 http://localhost:3000로 접속하면 잘 접속이 되지만 http://localhost:3000/section0909-04-boards 이렇게 접속하면 404에러가 뜹니다. 실행은 cs class로 이동 후 했습니다~
react node.js seo graphql next.js
wizitbiz
2024-01-07T02:37:54.490Z
댓글 2
좋아요 0
조회수 1145
해결됨
스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술
학습하는 분들께 도움이 되고, 더 좋은 답변을 드릴 수 있도록 질문전에 다음을 꼭 확인해주세요. 1. 강의 내용과 관련된 질문을 남겨주세요. 2. 인프런의 질문 게시판과 자주 하는 질문(링크)을 먼저 확인해주세요. (자주 하는 질문 링크: https://bit.ly/3fX6ygx) 3. 질문 잘하기 메뉴얼(링크)을 먼저 읽어주세요. (질문 잘하기 메뉴얼 링크: https://bit.ly/2UfeqCG) 질문 시에는 위 내용은 삭제하고 다음 내용을 남겨주세요. ========================================= [질문 템플릿] 1. 강의 내용과 관련된 질문인가요? (예/아니오) 2. 인프런의 질문 게시판과 자주 하는 질문에 없는 내용인가요? (예/아니오) 3. 질문 잘하기 메뉴얼을 읽어보셨나요? (예/아니오) [질문 내용] 처음 강사님께서 save 메서드에서는 @Test public void save(){ Member member = new Member(); member.setName("Spring"); repository.save(member); Member result = repository.findById(member.getId()).get(); Assertions.assertThat(member).isEqualTo(result); } 처럼 assertThat(member) 를 넣고 그 다음 isEqualTo(result)를 넣어 사용하셨는데, 이후에 findByName 에서는 @Test public void findByName(){ Member member1 = new Member(); member1.setName("spring1"); repository.save(member1); Member member2 = new Member(); member2.setName("spring2"); repository.save(member2); Member result = repository.findByName("spring2").get(); Assertions.assertThat(result).isEqualTo(member1); } 이처럼 result가 먼저 나오고 그 다음 member를 넣어 사용하십니다. 혹시 무슨 차이일까요?
병권
2024-01-07T02:35:46.965Z
댓글 1
좋아요 2
조회수 901
해결됨
[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
로그인 리프레시 토큰 수업에서 오류가 발생하여 문의드립니다. 로그인을 하고 login-success 페이지로 넘어간 후 버튼클릭을 하면 ApolloError: Cannot read property '_id' of null 오류가 발생합니다. staus code는 200로 보여집니다. 문제가 어떤것인지 모르겠는데 확인부탁드려요.
react node.js seo graphql next.js
suny_fun
2024-01-06T12:28:03.739Z
댓글 2
좋아요 0
조회수 340
미해결
[리뉴얼] React로 NodeBird SNS 만들기
안녕하세요 제로초님! 항상 강의 잘 보고 있고 질문에 답해주셔서 감사합니다! 섹션5 Next.js 서버사이드렌더링 CSS 서버사이드렌더링 강의 끝까지 진행한 수강생 입니다! 해당 강의 영상의 2분 45초에서 styled component 진짜로 서버사이드 렌더링 하려면 포스트맨에서 게시글에 대한 주소 입력 후 send를 눌렀을 때 화면에 styled component가 떠야 한다고 말씀하셨습니다! send 후 아래의 화면과 같이 뜨는데 CSS 서버사이드 렌더링이 제대로 된 게 맞는 건지 궁금합니다! ++++++ 추가 질문입니다..! <NextScript /> 위에 <script src= "https://polyfill.io/v3/polyfill.min.js? ......" /> 처럼 코드를 넣지 않아도 되나요? 아래 질문 글의 작성자님처럼 io부분을 넣지 않아도 코드가 정상적으로 작동되기에 질문 드립니다! https://www.inflearn.com/course/lecture?courseSlug=%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&unitId=48856&category=questionDetail&tab=community&q=128118 ++++++++++
react redux node.js express next.js
이가은
2024-01-06T10:49:07.086Z
댓글 1
좋아요 0
조회수 253
해결됨
실전! 스프링 부트와 JPA 활용1 - 웹 애플리케이션 개발
[질문 템플릿] 1. 강의 내용과 관련된 질문인가요? (예) 2. 인프런의 질문 게시판과 자주 하는 질문에 없는 내용인가요? (예) 3. 질문 잘하기 메뉴얼을 읽어보셨나요? (예) [질문 내용] 프로젝트 환경설정을 마치고 프로젝트를 돌려봤습니다. 똑같이 따라하면서요. 그런데 사진과 같이 create문까지 잘 나오는데 h2에 테이블이 안보여요 문제가 뭘까요? ㅠㅠ 주의 사항도 다 보면서 버전업 시켰는데도 안되네요.. 하루종일 구글링하고 찾아봐도 모르겠어요 도와주시면 감사하겠습니다
java spring 웹앱 spring-boot jpa
김현민
2024-01-06T08:41:14.572Z
댓글 1
좋아요 0
조회수 553
미해결
[리뉴얼] React로 NodeBird SNS 만들기
안녕하세요 선생님 상황) 쿠키/세션 전체 로그인 흐름 강좌를 따라해보았는데 로그인을 했을 때 401 에러가 발생하는 상황입니다. 시도해본 것) 아래 파일들의 로그인과 관련된 코드에 로그를 찍어보았고 이런 결과가 출력 되었습니다. 1)LoginForm => onSubmitForm함수에서 email,password찍으면 이메일,비밀번호 출력됨 2)reducers/user => loginRequestAction함수에서 data찍으면 이메일만 출력되고 loginAction함수에서는 출력안됨 3)sagas/user => logIn함수에서 action.data에 이메일만 출력되고 result는 출력안됨 4)user/routes => err는 null, user는 false, info는 { message: 'Missing credentials' }라고 출력됨 5)passport/index, passport/local => 출력안됨 질문1) reducer와 sagas에서는 원래 비밀번호가 출력이 안되는게 맞나요? 질문2) 만약에 reducer와 sagas에서 원래 비밀번호가 안나오는게 맞다면 어떤 부분에 문제가 있어서 reducer와 saga에서 data 나오는데, routes에서는 users가 false로 나오고 Missing credentials가 나오는건가요? 질문3)이 문제를 어떻게 해결하면 좋을까요,,? 작성한 코드) 글자수 제한이 있어 로그인 부분만 올립니닷,,! LoginForm import React, { useCallback, useEffect } from 'react'; import {Form, Input, Button} from 'antd'; import Link from 'next/link'; import styled from 'styled-components'; import {useDispatch, useSelector} from 'react-redux'; import useInput from '../hooks/useInput'; import {loginRequestAction} from '../reducers/user'; const LoginForm = () => { const dispatch = useDispatch(); const {logInLoading, logInError} = useSelector((state) => state.user); const [email, onChangeEmail] = useInput(''); const [password, onChangePassword] = useInput(''); useEffect(() => { if (logInError) { alert(logInError); } }, [logInError]); const onSubmitForm = useCallback(() => { console.log('LoginForm에서 email, password', email, password); //email, password luckyhaejin1@naver.com 1234 dispatch(loginRequestAction(email, password)); },[email, password]); return ( <FormWrapper onFinish={onSubmitForm}> {/* 생략 */} <Button type="primary" htmlType="submit" loading={logInLoading}>로그인</Button> </FormWrapper> ); } reducers/user import {produce} from 'immer'; export const initialState = { logInLoading: false, //login시도중 logInDone: false, logInError: null, //생략 loginData:{} } export const LOG_IN_REQUEST = 'LOG_IN_REQUEST'; export const LOG_IN_SUCCESS = 'LOG_IN_SUCCESS'; export const LOG_IN_FAILURE = 'LOG_IN_FAILURE'; export const loginAction = (data) => { console.log('reducers loginAction에서 data', data);//로그x return (dispatch) => { setTimeout(() => { dispatch(loginRequestAction()); }, 2000); dispatch(loginRequestAction()); } } export const loginRequestAction = (data) => { console.log('reducers loginRequestAction에서 data', data); //luckyhaejin1@naver.com return { type: LOG_IN_REQUEST, data } } const reducer = (state = initialState, action) => produce(state, (draft) => { switch(action.type){ case LOG_IN_REQUEST: draft.logInLoading = true; draft.logInError = null; draft.logInDone = false; break; case LOG_IN_SUCCESS: draft.logInLoading = false; draft.logInDone = true; draft.me = action.data; break; case LOG_IN_FAILURE: draft.logInLoading = false; draft.logInError = action.error; break; //생략 } }); export default reducer; sagas/user import axios from 'axios'; import { all, call, delay, fork, put, takeLatest } from 'redux-saga/effects'; import { LOG_IN_FAILURE, LOG_IN_REQUEST, LOG_IN_SUCCESS, } from '../reducers/user'; function logInAPI(data){ return axios.post('/user/login', data); } function* logIn(action) { try { console.log('sagas에서 action.data', action.data);//luckyhaejin1@naver.com const result = yield call(logInAPI, action.data); console.log('sagas에서 logIn함수에서 result', result);//로그x yield put({ type: LOG_IN_SUCCESS, data: result.data, }); } catch(err) { console.error(err); yield put({ type: LOG_IN_FAILURE, data: err.response.data, }); } } function* watchLogIn() { yield takeLatest(LOG_IN_REQUEST, logIn); } export default function* userSaga() { yield all ([ fork(watchLogIn) ]) } routes/user const express = require('express'); const bcrypt = require('bcrypt'); const {User} = require('../models'); const router = express.Router(); const passport = require('passport'); router.post('/login',(req, res, next)=> { console.log('routes 진입'); passport.authenticate('local',(err, user, info) => { if(err) { console.error(err); return next(err); } if(info) { console.log('routes err', err);//null console.log('routes user', user);//false console.log('routes info', info);//{ message: 'Missing credentials' } return res.status(401).send(info.reason); } return req.login(user,async(loginErr)=> { if(loginErr) { console.log('routes loginErr', loginErr); console.error(loginErr); return next(loginErr); } return res.status(200).json(user); }); })(req, res, next); }); //POST /user/login module.exports = router; passport/index const passport = require('passport'); const local = require('./local'); const { User } = require('../models'); module.exports = () => { passport.serializeUser((user,done) => { console.log('serializeUser의 user.id', user.id);//로그x done(null,user.id);//첫번째 인자 에러, 두번째 인자 성공(쿠키와 묶어줄 user아이디만 저장) }); passport.deserializeUser(async(id, done) => { try { const user = await User.findOne({where:{id}}) console.log('deserializeUser의 user', user);//로그x done(null,user); } catch(error) { console.error(error); done(error); } }); local(); }; passport/local const passport = require('passport'); const {Strategy:LocalStrategy} = require('passport-local'); const bcrypt = require('bcrypt'); const {User} = require('../models'); const express = require('express'); const router = express.Router(); router.post('/login', passport.authenticate('local')); module.exports = () => { passport.use(new LocalStrategy({ usernameField: 'email', passwordField: 'password', }, async(email, password, done) => { console.log('Passport LocalStrategy - Start');//로그x try { const user = await User.findOne({ where:{email} }); if(!user) { console.log('Passport LocalStrategy - User not found');//로그x return done(null, false, {reasone: '존재하지 않는 이메일입니다!'}) } const result = await bcrypt.compare(password, user.password); if(result) { console.log('Passport LocalStrategy - Login success');//로그x return done(null, user);//성공에 사용자 정보 넘겨줌 } console.log('Passport LocalStrategy - Incorrect password');//로그x return done(null, false, {reason:'비밀번호가 틀렸습니다.'}); } catch(error) { console.error('Passport LocalStrategy - Error:', error);//로그x return done(error); } })); } 사용중인 OS) macOS Apple M1 Pro 설치된 버전) back/Package.json "dependencies": { "passport": "^0.7.0", "passport-local": "^1.0.0", "sequelize": "^6.35.2", "sequelize-cli": "^6.6.2" },
react redux node.js express next.js
박해진
2024-01-06T07:17:44.805Z
댓글 2
좋아요 0
조회수 452
미해결
Next + React Query로 SNS 서비스 만들기
페러랠모달이 뜬 후에 뒷쪽 페이지의 스크롤과, 페럴랠모달의 오른쪽 코멘츠부분의 스크롤이 겹치는 이슈가 있습니다. 해당사항 진도빼면 뒷쪽 강의중간에 해결되는지 궁금합니다. 이걸 해결하려면 모달이 뜬것을 감지하여 뒷쪽 페이지 스크롤을 스크롤을 막고, 모달이 꺼진걸 감지해서 다시 뒷쪽 페이지의 스크롤을 활성화 해야할거같은데... 모달이 뜬것을 감지할 수 있나요?
react next.js react-query next-auth msw
라푼젤
2024-01-05T12:28:27.029Z
댓글 1
좋아요 0
조회수 449
해결됨
[리뉴얼] React로 NodeBird SNS 만들기
import React, { useState } from "react"; const ToggleButtons = () => { const [buttonAActive, setButtonAActive] = useState(false); const [buttonBActive, setButtonBActive] = useState(false); const handleButtonClick = (button) => { if (button === "A") { setButtonAActive((prev) => !prev); setButtonBActive(false); } else if (button === "B") { setButtonBActive((prev) => !prev); setButtonAActive(false); } }; return ( <div> <button onClick={() => handleButtonClick("A")} style={{ backgroundColor: buttonAActive ? "green" : "white" }} > Button A </button> <button onClick={() => handleButtonClick("B")} style={{ backgroundColor: buttonBActive ? "red" : "white" }} > Button B </button> </div> ); }; next js로 버튼 A와 B가 있는데 A가 켜져있는 상태에서 B를 누르면 A가 꺼지고 B가 켜져있는 상태에서 A를 누르면 꺼지고 A가 켜져있는 상태에서 A를 또 누르면 꺼지고 B를 누른 상태에서 B를 또 누르면 꺼지는 버튼 2개를 만들고 있는데 이렇게 코드를 작성하니까 무한 렌더링이 걸리는데 해결 방법이 있을까요?
react redux node.js express next.js
i1004gy
2024-01-05T11:26:56.071Z
댓글 2
좋아요 0
조회수 471
해결됨
Next + React Query로 SNS 서비스 만들기
loginForm 컴포넌트에서 로그인시 '/' path로 보내려고 하는데 위와같은 오류가 뜨면서 진행대지 않습니다. baseUrl 찾아보니 default 값이 localhost:3000 으로 설정된걸 확인했습니다. 진짜 이리저리 찾아봤는데도 해결방법을 찾아볼수없어서 문의드립니다. 구글링한 방법중에 await 말고 then catch로 하면 댄다는글도 봐서 해봤는데도 오류가 그대로 나왔습니다. 서버랑 문제없이 잘됩니다.
react next.js react-query next-auth msw
아지르
2024-01-05T11:01:03.626Z
댓글 2
좋아요 0
조회수 357