173만명의 커뮤니티!! 함께 토론해봐요.
미해결
코드로 배우는 React 19 with 스프링부트 API서버
8강 10분56초에서 하늘색 허공에 클릭하시는데 페이지가 이동하는것 같은데요. 어떻게 하신것인지 궁금해서 질문드립니다. 글자를 클릭해야 하는것 아닌가요? 근데 영상에서 동작은 또 잘되네요...?... 제가 잘 몰라서 이해를 잘못한걸까여?... 아래는 제 코드입니다..
react spring-boot jpa jwt redux-toolkit
전경환
2024-01-08T09:51:55.409Z
댓글 1
좋아요 0
조회수 274
해결됨
Next.js 필수 개발 가이드 3시간 완성!
안녕하세요 ! APIs 생성하기 섹션을 들으며 연습하고 있는데요. 사용자 ID 값이 10 보다 큰 경우에는 404 에러를 출력하고 나머지 경우에는 사용자 정보를 반환하도록 작성해주신 GET 메서드 코드를 따라 작성했고, 포스트맨에서 정상 작동함을 확인하였습니다. 강사님 코드 import { NextRequest, NextResponse } from "next/server"; export function GET( request: NextRequest, { params }: { params: { id: number } } ) { // 사용자 ID 값이 10보다 큰 경우 404 오류 출력 if (params.id > 10) { return NextResponse.json({ error: "USER NOT FOUND" }, { status: 404 }); } // 사용자 정보를 응답으로 전달 return NextResponse.json([ { id: 1, name: "Jieun" }, { id: 2, name: "Hansol" }, ]); } 따라하다가 문득, 전체 사용자 정보가 아니라 해당 id 에 해당하는 사용자 정보를 출력하고 싶어, 아래와 같이 코드를 수정하였습니다. 코드에 문제가 없다 생각했는데 에러를 출력하더라구요 ㅠㅠ 에러 코드 import { NextRequest, NextResponse } from "next/server"; export function GET( request: NextRequest, { params }: { params: { id: number } } ) { const userData = [ { id: 1, name: "Jieun" }, { id: 2, name: "Hansol" }, ]; const user = userData.find((user) => user.id === params.id); if (!user) { return NextResponse.json( { error: "사용자를 찾을 수 없습니다" }, { status: 404 } ); } return NextResponse.json(user); } `user` 를 잘 찾지 못하는 것 같아서 혹시 id 타입 문제인가 해서 params.id 의 타입을 바꾸고 실행하였더니 정상 작동 하였습니다. 정상 작동했던 코드 1 import { NextRequest, NextResponse } from "next/server"; export function GET( request: NextRequest, { params }: { params: { id: string } } ) { const userData = [ { id: 1, name: "Jieun" }, { id: 2, name: "Hansol" }, ]; const requestedId = parseInt(params.id); const user = userData.find((user) => user.id === requestedId); if (!user) { return NextResponse.json( { error: "사용자를 찾을 수 없습니다" }, { status: 404 } ); } return NextResponse.json(user); } 정상 작동했던 코드 2 import { NextRequest, NextResponse } from "next/server"; export function GET( request: NextRequest, { params }: { params: { id: number } } ) { // Mock user data const userData = [ { id: 1, name: "Jieun" }, { id: 2, name: "Hansol" }, ]; const requestedId = typeof params.id === "string" ? parseInt(params.id, 10) : params.id; const user = userData.find((user) => user.id === requestedId); if (!user) { return NextResponse.json( { error: "사용자를 찾을 수 없습니다" }, { status: 404 } ); } // Return the user information return NextResponse.json(user); } 질문입니다! API 호출 시 전달되는 매개변수 params.id 의 타입은 GET 메소드 매개변수 선언시 지정해주는 타입으로 정해지는건가요? string 타입인거라면 강사님 코드가 실행되지 않았어야 하고, number 타입이라면 저의 에러코드 또한 실행되었어야 하는데 왜 정상적으로 작동하지 않았는지 궁금합니다.
react typescript next.js ssr
달지
2024-01-08T09:26:29.320Z
댓글 1
좋아요 1
조회수 268
미해결
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
미해결
[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
강의 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
조회수 192
해결됨
[리뉴얼] 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
미해결
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
조회수 477
미해결
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
미해결
파이썬으로 영화 예매 오픈 알리미 만들기
해당 강의에서 작성하는 코드를 그대로 실행하면 되지 않습니다. 현재 iframe 태그가 자바스크립트를 통해 실행되기 때문에 페이지가 로드된 후에도 자바스크립트가 실행될 시간이 필요합니다. 강의처럼 iframe의 주소만 따와서 실행시키는 것이 아닌 전체 주소를 가져와 iframe 태그로 전환시켜주고 자바스크립트 실행까지 기다려 주는 방식으로 진행하셔야 합니다. https://velog.io/@os_js/%ED%8C%8C%EC%9D%B4%EC%8D%AC-%EC%9B%B9-%ED%81%AC%EB%A1%A4%EB%A7%81%EC%9D%B4%EC%9A%A9-%ED%85%94%EB%A0%88%EA%B7%B8%EB%9E%A8-%EC%B1%97%EB%B4%87 저도 강의중 안됐던 내용이 있었기에 그에 대한 내용을 블로그에 올려두었습니다. 강의 진행대로 따라하다가 안되는 부분만 정리하여 올렸기 때문에 강의내용과 비교하시면서 보셔야 될 듯 합니다.
나도했음
2024-01-07T11:50:18.510Z
댓글 1
좋아요 0
조회수 612
해결됨
[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
기존 노트북에서는 잘 되었다가 다른 노트북에서 깃허브에서 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
조회수 1146
해결됨
[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
로그인 리프레시 토큰 수업에서 오류가 발생하여 문의드립니다. 로그인을 하고 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
조회수 254
미해결
[리뉴얼] 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
조회수 453
미해결
Next + React Query로 SNS 서비스 만들기
페러랠모달이 뜬 후에 뒷쪽 페이지의 스크롤과, 페럴랠모달의 오른쪽 코멘츠부분의 스크롤이 겹치는 이슈가 있습니다. 해당사항 진도빼면 뒷쪽 강의중간에 해결되는지 궁금합니다. 이걸 해결하려면 모달이 뜬것을 감지하여 뒷쪽 페이지 스크롤을 스크롤을 막고, 모달이 꺼진걸 감지해서 다시 뒷쪽 페이지의 스크롤을 활성화 해야할거같은데... 모달이 뜬것을 감지할 수 있나요?
react next.js react-query next-auth msw
라푼젤
2024-01-05T12:28:27.029Z
댓글 1
좋아요 0
조회수 450
해결됨
[리뉴얼] 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
조회수 472
해결됨
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
미해결
Next + React Query로 SNS 서비스 만들기
page.module.css 가 깃허브에 없어요 제가 설치한 page.module.css와 다소 달라서 복붙할려고 했떠니 제로초님 깃허브에는 layout.module.css 가 있네요 일단 css적용이 안되지만 진행해보겠습니다!
react next.js react-query next-auth msw
김형
2024-01-05T09:51:03.620Z
댓글 1
좋아요 0
조회수 596