173만명의 커뮤니티!! 함께 토론해봐요.
해결됨
[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
안녕하세요, indexOf 메소드를 사용하다가 -1 값이 변환되었습니다. 파이썬에서는 인덱스가 -1이라면 맨마지막에 있는 인덱스 순서를 의미하는데 자바스크립트는 의미가 다른가요?자바스크립트에서 가지는 '-1'의 의미가 궁금합니다. 코드를 보시면 제가 indexOf 메소드 값 안에 오타를 넣었습니다.오류가 날 줄 알았는데 오타의 인덱스 값이 -1이 반환되어서 -1 값이 나온 이유에 대해 설명 부탁드립니다. 감사합니다. 수업 잘 듣고 있습니다. :)
react node.js seo graphql next.js
유클리드소프트
2023-11-07T11:46:57.869Z
댓글 3
좋아요 0
조회수 424
미해결
[리뉴얼] 처음하는 파이썬 데이터 분석 (쉽게! 전처리, pandas, 시각화 전과정 익히기) [데이터분석/과학 Part1]
위 코드를 실행하니 'could not convert string to float: 'Abbeville' 라는 에러가 전시됩니다. Abbeville를 float으로 바꿀 수가 있나요?
이희동
2023-11-07T11:00:46.893Z
댓글 1
좋아요 0
조회수 311
해결됨
React + GPT API로 AI회고록 서비스 개발 (원데이 클래스)
setUserInput("")을 하면 userInput 값이 ""로 바뀌고 그다움 num 선언문에 ""의 숫자변환값이 들어가는게 아닌가 궁금합니다.
HTML/CSS javascript react node.js chatgpt
최지훈
2023-11-07T02:10:01.730Z
댓글 2
좋아요 2
조회수 348
해결됨
[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
next 14 버전부터 next export 가 없어지고 next.config.js 파일에서 output: "export" 로 대체되었다는데 이대로 진행해도 문제 없을까요?
react node.js seo graphql next.js
kyb1208tg
2023-11-06T11:55:54.458Z
댓글 1
좋아요 0
조회수 1181
해결됨
[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
비밀번호와 비밀번호 확인이 서로 일치하는지 검증하는 코드를 어떻게 짜야할 지 모르겠어요.. 현재 코드로 하면 에러가 납니다..! 봐주시면 감사하겠습니다ㅠㅠ 해당코드 //문제부분!!!!!!!!!!!!!!!!!!!!********* 으로 해놓았습니다!! import { useState } from 'react'; export default function signUpPage() { //이메일, 비밀번호 담기 const [ email, setEmail ] = useState(""); const [ password, setPassWord ] = useState(""); const [ Repassword, setRePassWord ] = useState(""); //이메일 에러 const [ emailError, setEmailError ] = useState(""); //비밀번호 에러 const [ passWordError, setPassWordError ] = useState(""); //비밀번호확인 에러 const [ RepassWordError, setRePassWordError ] = useState(""); //이메일 const onChangeEmail = (event) =>{ //이벤트 핸들러 console.log(event); console.log(event.target); //작동된 태그 console.log(event.target.value); //작동된 태그에 입력된 값 //변경된 이메일 값을 넣음 setEmail(event.target.value); if(event.target.value !== ''){ //내용 입력시 에러 없애주는거 setEmailError(""); } } const onChangePassWord = (event) => { setPassWord(event.target.value); if(event.target.value !== ''){ setPassWordError(""); } } //문제부분!!!!!!!!!!!!!!!!!!!!********* const onChangeRePassWord = (event) => { // const currentPassWord = event.target.value; // setRePassWord(currentPassWord); // if(password === currentPassWord){ // setRePassWordError(""); // } setRePassWord(event.target.value); if((password === Repassword()) || (event.target.value !== '')){ setRePassWordError(""); } } //등록하기 버튼 에러검증 const onClickSign = () => { //이메일 @ 검증 //includes("") 해당 문자가 있냐 없냐 if(email.includes("@") === false) { setEmailError("이메일이 올바르지 않습니다. @ 형태로 입력해주세요!") } if(!password){ setPassWordError("비밀번호를 입력해주세요") } //문제부분!!!!!!!!!!!!!!!!!!!!********* if((password !== Repassword) || (!Repassword)){ setRePassWordError("비밀번호를 확인해주세요") } //회원가입 완료 if(email && password === Repassword) { alert("회원가입이 완료되었습니다") } } return( <> 이메일: <input type="text" onChange={onChangeEmail} /> <div>{emailError}</div> 비밀번호 :<input type="text" onChange={onChangePassWord} /> <div>{passWordError}</div> 비밀번호확인 :<input type="text" onChange={onChangeRePassWord} /> <div>{RepassWordError}</div> <button id="submit" onClick={onClickSign}>회원가입</button> </> ) }
react node.js seo graphql next.js
윰이
2023-11-06T08:22:36.550Z
댓글 1
좋아요 0
조회수 293
해결됨
[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
'Assertion' 형식에 'toBe' 속성이 없습니다. 이 오류가 jest관련 toBe, toEqual, toBeInTheDocument등에 다 뜹니다
react node.js seo graphql next.js
김무연
2023-11-06T02:48:22.006Z
댓글 1
좋아요 1
조회수 477
해결됨
[리뉴얼] React로 NodeBird SNS 만들기
상세이미지에서 전체화면까지는 되었는데, 이미지가 안 떠서 질문드립니다 밑에 이미지 Indicator를 보면 스크롤하면 다음으로 넘어가는 기능은 잘 작동하는 것 같은데 이미지 불러오기가 안 되는 것 같습니다만 이유를 모르겠습니다.. 컴파일도 잘 되었구요ㅠ ImagesZoom/index.js 코드 첨부합니다 const ImagesZoom = ({ images, onClose }) => { const [currentSlide, setCurrentSlide] = useState(0); return ( <Overlay> <Global /> <Header> <h1>상세 이미지</h1> <CloseBtn onClick={onClose}>X</CloseBtn> </Header> <SlickWrapper> <div> <Slick initialSlide={0} beforeChange={(slide) => setCurrentSlide(slide)} infinite arrows={false} slidesToShow={1} slidesToScroll={1} > {images.map((v) => ( <ImgWrapper key={v.src}> <img src={v.src} alt={v.src} /> </ImgWrapper> ))} </Slick> <Indicator> <div> {currentSlide + 1} {' '} / {images.length} </div> </Indicator> </div> </SlickWrapper> </Overlay> ); }; PostImages.js 코드입니다 const PostImages = ({ images }) => { const [showImagesZoom, setShowImagesZoom] = useState(false); const onZoom = useCallback(() => { setShowImagesZoom(true); }, []); const onClose = useCallback(() => { setShowImagesZoom(false); }, []); if (images.length === 1) { return ( <> <img role="presentation" src={images[0].src} alt={images[0].src} onClick={onZoom} /> {showImagesZoom && <ImagesZoom images={images} onClose={onClose} />} </> ); } if (images.length === 2) { return ( <> <div> <img style={{ width: "50%", display: 'inline-block' }} role="presentation" src={images[0].src} alt={images[0].src} onClick={onZoom} /> <img style={{ width: "50%", display: 'inline-block' }} role="presentation" src={images[1].src} alt={images[1].src} onClick={onZoom} /> </div> {showImagesZoom && <ImagesZoom images={images} onClose={onClose} />} </> ); } return ( <> <div> <img style={{ width: "50%" }} role="presentation" src={images[0].src} alt={images[0].src} onClick={onZoom} /> <div role="presentation" style={{ display: 'inline-block', width: '50%', textAlign: 'center', verticalAlign: 'middle' }} onClick={onZoom} > <PlusOutlined /> <br /> {images.length - 1}개의 사진 더보기 </div> </div> {showImagesZoom && <ImagesZoom images={images} onClose={onClose} />} </> ); };
react redux node.js express next.js
sscapstondesign3
2023-11-05T02:37:46.042Z
댓글 2
좋아요 0
조회수 807
미해결
[리뉴얼] React로 NodeBird SNS 만들기
이미지 업로드를 위한 multer 강의까지 수강을 하였습니다. 이미지 업로드를 할때 uploads 폴더에도 이미지가 잘 들어가고 UPLOAD_IMAGES_SUCCESS도 잘 나오는 상황입니다. 하지만 제로초님의 화면은 제거 버튼과 비록 깨지지만 이미지가 올라간 화면이 보이는데 저는 그 부분이 나오지 않아서 이 점이 궁금하여 질문 드립니다. import React, { useState } from "react"; import { Button, Card, Popover, Avatar, Image, List, Comment } from "antd"; import { RetweetOutlined, HeartOutlined, MessageOutlined, EllipsisOutlined, HeartTwoTone, } from "@ant-design/icons"; import { useCallback } from "react"; import { useSelector, useDispatch } from "react-redux"; import PropTypes from "prop-types"; import PostImages from "./PostImages"; import CommentForm from "./CommentForm"; import PostCardContent from "./PostCardContent"; import { REMOVE_POST_REQUEST, LIKE_POST_REQUEST, UNLIKE_POST_REQUEST, } from "../reducers/post"; import FollowButton from "./FollowButton"; const PostCard = ({ post }) => { //pages/index.js에서 mainPosts에서 하나씩 뜯어서 보내줌 const dispatch = useDispatch(); const [commentFormOpened, setCommentFormOpened] = useState(false); //댓글창 열지 말지 const onLike = useCallback(() => { dispatch({ type: LIKE_POST_REQUEST, data: post.id, }); }, []); //좋아요 const onUnlike = useCallback(() => { dispatch({ type: UNLIKE_POST_REQUEST, data: post.id, }); }, []); //좋아요 취소 const onToggleComment = useCallback(() => { setCommentFormOpened((prev) => !prev); }, []); //폼 버튼 한번 더 누르면 폼 닫기 const onRemovePost = useCallback(() => { return dispatch({ type: REMOVE_POST_REQUEST, data: post.id, }); }, [id]); const id = useSelector((state) => state.user.me?.id); const { removePostloading } = useSelector((state) => state.post); const liked = post.Likers.find((v) => v.id === id); //게시글 좋아요 누른 사람 중에 내가 있는지. return ( <div style={{ marginBottom: 20 }}> <Card cover={post.Images?.[0] && <PostImages images={post.Images} />} //이미지가 존재한다면 PostImages를 출력 actions={[ //카드 아래에 존재하는 것들 <RetweetOutlined key="retweet" />, liked ? ( <HeartTwoTone twoToneColor="red" onClick={onUnlike} /> ) : ( <HeartOutlined key="heart" onClick={onLike} /> ), <MessageOutlined onClick={onToggleComment} key="comment" />, <Popover //더보기 같은 역할 key="more" content={ <Button.Group> {id && post.User.id === id ? ( <> {/* 내가 쓴 글이면 수정, 삭제 */} <Button>수정</Button> <Button type="danger" onClick={onRemovePost} loading={removePostloading} > 삭제 </Button> </> ) : ( // 내가 쓴 글이 아니라면 <Button>신고</Button> )} </Button.Group> } > <EllipsisOutlined /> </Popover>, ]} extra={id && <FollowButton post={post} />} > <Card.Meta //프로필과 내용 등 avatar={<Avatar>{post.User.nickname[0]}</Avatar>} title={post.User.nickname} description={<PostCardContent postData={post.content} />} /> </Card> {commentFormOpened && ( //commentFormOpened가 true이면 열어라 <div> {/* 어떤 게시글에 댓글을 남기는지.. */} <CommentForm post={post} /> <List header={`${post.Comments.length}개의 댓글`} itemLayout="horizontal" dataSource={post.Comments} //데이터는 여기서 가져와서 renderItem={( item //이런식으로 출력한다 ) => ( <li> <Comment author={item.User.nickname} //댓글쓴사람 avatar={ <Avatar>{item.User.nickname[0]}</Avatar> //아바타 } content={item.content} /> </li> )} /> </div> )} </div> ); }; PostCard.PropTypes = { post: PropTypes.shape({ id: PropTypes.number, User: PropTypes.object, content: PropTypes.string, createdAt: PropTypes.string, Comment: PropTypes.arrayOf(PropTypes.object), Images: PropTypes.arrayOf(PropTypes.object), Likers: PropTypes.arrayOf(PropTypes.object), }).isRequired, }; export default PostCard; 저의 PostCard 코드입니다 이 코드에서 cover={post.Images?.[0] && <PostImages images={post.Images} />} 이 부분이 이미지들을 출력해주는 부분이 아닌가요?? 저의 화면에는 아래처럼 나오지 않습니다.
react redux node.js express next.js
윤채현
2023-11-04T13:28:32.709Z
댓글 1
좋아요 0
조회수 382
미해결
따라하며 배우는 노드, 리액트 시리즈 - 레딧 사이트 만들기(NextJS)(Pages Router)
안녕하세요! 섹션2 수업내용까지 마치고 npm run dev를 하였는데 오류가 나타납니다 ;-; 커뮤니티에서 -61 에러 관련글을 찾아보니, 데이터베이스 연결 문제를 확인해보라고 하셨는데..;-; 연결 방법을 모르겠습니다.. package.json "main"이 index.ts로 되어있어서 server.ts로 바꾸었습니다. 그랬더니 ;-; 4000번이 열리긴 합니다. 그런데 터미널에는 여전히 오류가 함께 나타납니다!!;; 무엇을 확인해보면 될까요 ;-;..?
react node.js postgresql docker typescript 클론코딩 next.js
장진
2023-11-03T11:24:43.948Z
댓글 1
좋아요 0
조회수 380
미해결
[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
33-05 강의에서 test에서 자꾸 이 오류가 뜹니다 apis.js import { graphql } from "msw"; const gql = graphql.link("http://mock.com/graphql") export const apis = [ gql.mutation("createBoard", (req, res, ctx) => { const { writer, title, contents } = req.variables.createBoardInput return res( ctx.data({ createBoard: { _id: "qqq", writer, title, contents, __typepname: "Board", }, }) ); }), // gql.query("fetchBoards", () => {}) ]; jest.setup.js import { server } from "./src/commons/mocks/index" beforeAll(() => server.listen()); afterAll(() => server.close()); index.test.tsx import { fireEvent, render, screen, waitFor } from "@testing-library/react"; import StaticRoutingMovedPage from "../../pages/section33/33-05-jest-unit-test-mocking"; import { ApolloClient, ApolloProvider, HttpLink, InMemoryCache, } from "@apollo/client"; import fetch from "cross-fetch"; import mockRouter from "next-router-mock"; jest.mock("next/router", () => require("next-router-mock")); it("게시글이 잘 등록되는지 테스트 하자!", async () => { const client = new ApolloClient({ link: new HttpLink({ uri: "http://mock.com/graphql", fetch, }), cache: new InMemoryCache(), }); render( <ApolloProvider client={client}> <StaticRoutingMovedPage /> </ApolloProvider> ); fireEvent.change(screen.getByRole("input-writer"), { target: { value: "맹구" }, }); fireEvent.change(screen.getByRole("input-title"), { target: { value: "안녕하세요" }, }); fireEvent.change(screen.getByRole("input-contents"), { target: { value: "방가방가" }, }); fireEvent.click(screen.getByRole("submit-button")); await waitFor(() => { expect(mockRouter.asPath).toEqual("/boards/qqq"); }); }); 도와주십쇼 ㅠㅠ
react node.js seo graphql next.js
김무연
2023-11-03T07:22:46.450Z
댓글 4
좋아요 0
조회수 680
미해결
[리뉴얼] React로 NodeBird SNS 만들기
안녕하세요 제로초님! 게시글을 작성하게되면 아래와 같이 성공했다고 응답도 잘 도착하지만 id가 undefined이라고 오류가 납니다. 제가 어느 부분을 놓치고 있는건가요??
react redux node.js express next.js
윤채현
2023-11-02T15:26:50.010Z
댓글 1
좋아요 0
조회수 335
미해결
[리뉴얼] React로 NodeBird SNS 만들기
안녕하세요 제로초님 middleware.js를 사용하여 로그인했을때와 하지않았을 때의 경우를 나눠놓으셨자나요! 그 강좌를 듣고 코드를 그대로 작성하고 로그인을 진행해보는데 올바른 이메일과 비밀번호를 입력해도 이 알림이 뜹니다.. 로그인도 실패로 응답하구요.. 어떤 부분이 문제일 가능성이 높을까요??
react redux node.js express next.js
2023-11-02T14:45:38.524Z
댓글 1
좋아요 0
조회수 479
미해결
[개정판] 파이썬 머신러닝 완벽 가이드
강의 회귀 실습 1: 자전거 대여(공유) 수요 예측 -02에서 19분 52초 경에 나오는 선형 회귀의 피처별 회귀계수 시각화 부분에서 저 회귀계수 값들이 다르게 나올 수가 있는지, 질문드립니다. github의 주피터노트북 코드 다운로드 받아서 그대로 시행했는데 LinearRegression/Lasso/Ridge 각 회귀에 대한 RMSLE, RMSE, MAE까지는 값이 정확히 동일하게 나오는데 회귀 계수의 값을 보려고 lr_reg.coef_ 부분에서 결과가 다르게 나옵니다. 상식적으로 회귀 모형에서 이런 결과가 나올 수가 없다고 생각되는데 무슨 이유인지 모르겠어서 질문드립니다! 감사합니다
aloeeola
2023-11-02T11:52:36.722Z
댓글 3
좋아요 0
조회수 453
미해결
따라하며 배우는 리액트 네이티브 기초
<SafeAreaView> 써도 이러네요.. 환경은 윈도우, 안드로이드 스튜디오 pixel4 썼습니다
mozzzi.__
2023-11-02T09:48:31.927Z
댓글 3
좋아요 0
조회수 554
해결됨
[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
강의를 잘 따라가면서 작성하고 있었는데 화면을 최종적으로 확인할 때 이런 에러가 뜹니다. 코드를 두번확인했는데 틀린 부분이 보이지않습니다 ..! index.js 코드 입니다 import BoardWrite from '../../../src/components/units/board/write/BoardWrite.container' export default function GraphqlMutationPage(){ return ( <> <div>###### 여기는 페이지 입니다 ######</div> {/* //로직을 가져옴 */} <BoardWrite /> <div>###### 여기는 페이지 입니다 ######</div> </> ) } BoardWrite.container.js 코드 입니다 import { useMutation } from '@apollo/client' import {useState} from 'react' //UI를 가져옴(파일을 합침) import BoardWriterUI from './BoardWrite.presenter' //gql 가져옴(파일을 합침) import {나의그래프큐엘셋팅} from './BoardWrite.queries' //로직만 사용 export default function BoardWrite() { const [writer, setWriter] = useState() const [title, setTitle] = useState() const [contents, setContents] = useState() const [나의함수] = useMutation(나의그래프큐엘셋팅); const onClickSubmit = async () => { const result = await 나의함수({ variables: { writer: writer, title: title, contents: contents } }) console.log(result) }; const onChangeWriter = (event) => { setWriter(event.target.value) // => state에 저장 } const onChangeTitle = (event) => { setTitle(event.target.value) } const onChangeContents = (event) => { setContents(event.target.value) } return( <> <div>$$$$$$$ 여기는 컨테이너 입니다 $$$$$$</div> {/* UI를 가져옴(파일을 합침) */} <BoardWriterUI aaa={onClickSubmit} bbb={onChangeWriter} ccc={onChangeTitle} ddd={onChangeContents} /> <div>$$$$$$$ 여기는 컨테이너 입니다 $$$$$$</div> </> ) } BoardWrite.presenter.js 코드 입니다 import {BlueButton, RedInput } from './BoardWrite.style' //UI만 사용 export default function BoardWriterUI(props){ return( <> <div>@@@@@@@@ 여기는 프리젠터 입니다 @@@@@@@</div> <div> 작성자: <RedInput type="text" onChange={props.bbb} /> 제목: <input type="text" onChange={props.ccc} /> 내용: <input type="text" onChange={props.ddd} /> <BlueButton onClick={props.aaa}>GRAPHQL-API 요청하기</BlueButton> </div> <div>@@@@@@@@ 여기는 프리젠터 입니다 @@@@@@@</div> </> ) } BoardWrite.queries.js 코드 입니다 import { gql } from '@apollo/client' export const 나의그래프큐엘셋팅 = gql` mutation createBoard($writer: String, $title: String, $contents: String){ createBoard(writer : $writer , title: $title , contents: $contents) { _id number message } } BoardWrite.style.js 코드 입니다 import styled from '@emotion/styled' export const RedInput = styled.input` border-color: red; ` export const BlueButton = styled.button` background-color: blue; ` app.js 코드 입니다 // 모든 페이지의 공통설정들 여기서 진행 import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client' export default function App({ Component, pageProps }) { const client = new ApolloClient({ uri:"http://backend-example.codebootcamp.co.kr/graphql", cache: new InMemoryCache() //컴퓨터의 메모리에다가 백엔드에서 받아온 데이터 임시로 저장해 놓기 => 나중에 더 자세히 알아보기 }) return ( <div> <div> ========== 여기는 _app.js 컴포넌트 시작부분 입니다. ==========</div> {/* //그래프큐엘 셋팅 => 앞으로 아래 컴포넌트에서 client를 쓸 수 있다는 의미 */} <ApolloProvider client={client}> <Component /> {/* 내가 들어간 페이지들의 html이 여기로 다 들어오게 됨 */} </ApolloProvider> <div> ========== 여기는 _app.js 컴포넌트 마지막부분 입니다. ==========</div> </div> ) } 마지막으로 폴더 구조입니다
react node.js seo graphql next.js
윰이
2023-11-02T06:43:57.085Z
댓글 1
좋아요 0
조회수 252
해결됨
[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
boards/new/index.js 에서 항목 기입 후 등록하기 버튼을 누를 시 등록된 상세페이지로 넘어가지 않고 alert 알림창으로 "Response not successful: Received status code 400" 이렇게 뜹니다. 오타는 혹시 있나 해서 올려주신 깃허브랑 하나하나 꼼꼼히 비교 했는데 없었어요.. 오류코드를 개발자도구로 뜯어보니 그래서 해당 부분 확인해봐도 모두 강사님과 동일하게 작성되있는데 뭐가 문제일까요
react node.js seo graphql next.js
초록
2023-11-02T06:35:08.521Z
댓글 1
좋아요 0
조회수 317
미해결
스프링 시큐리티 OAuth2
authenticastion Entry Point로 지정 시 cors문제가 계속해서 진행되어 Authorization Code를 받아올 수 없습니다. 코드 첨부 Authorization Server Config @Bean @Order(Ordered.HIGHEST_PRECEDENCE) public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http); http .getConfigurer(OAuth2AuthorizationServerConfigurer.class) .oidc(Customizer.withDefaults() ); http .exceptionHandling((exceptions) -> exceptions .authenticationEntryPoint( new LoginUrlAuthenticationEntryPoint("http://localhost:3000") // new LoginUrlAuthenticationEntryPoint("/login") )) http.oauth2ResourceServer((resourceServer) -> resourceServer .jwt(Customizer.withDefaults())); return http.build(); } @Bean public RegisteredClientRepository registeredClientRepository() { RegisteredClient oidcClient = RegisteredClient.withId(UUID.randomUUID().toString()) .clientId("oidc-client") .clientSecret("{noop}secret") .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN) .redirectUri("https://oidcdebugger.com/debug") .redirectUri("https://test-b821b.web.app") .postLogoutRedirectUri("http://127.0.0.1:8080/") .scope(OidcScopes.OPENID) .scope(OidcScopes.PROFILE) .clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build()) .build(); return new InMemoryRegisteredClientRepository(oidcClient); } @Bean public AuthorizationServerSettings authorizationServerSettings() { return AuthorizationServerSettings.builder().issuer("http://localhost:6080").build(); } } Default Web Config @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("http://localhost:3000") .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .allowedHeaders("*") .allowCredentials(true) .exposedHeaders("*"); } }; } @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowCredentials(true); configuration.addAllowedHeader("*"); configuration.addAllowedMethod("*"); configuration.addAllowedOrigin("http://localhost:3000"); configuration.setExposedHeaders(Arrays.asList("*")); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .cors(customCorsConfig -> customCorsConfig.configurationSource(corsConfigurationSource())) .csrf(AbstractHttpConfigurer::disable) .authorizeHttpRequests(authorizeHttpRequestsCustomizer -> authorizeHttpRequestsCustomizer.requestMatchers(AUTH_WHITELIST).permitAll() .anyRequest().authenticated() ) .formLogin( httpSecurityFormLoginConfigurer -> httpSecurityFormLoginConfigurer.loginPage("http://localhost:3000").loginProcessingUrl("/login") // Customizer.withDefaults() ) ; return http.build(); } @Bean public UserDetailsService userDetailsService() { PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); UserDetails userDetails = User.builder() .username("user") .password(passwordEncoder.encode("password")) .roles("USER") .build(); return new InMemoryUserDetailsManager(userDetails); } @Bean public JWKSource<SecurityContext> jwkSource() { KeyPair keyPair = generateRsaKey(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); RSAKey rsaKey = new RSAKey.Builder(publicKey) .privateKey(privateKey) .keyID(UUID.randomUUID().toString()) .build(); JWKSet jwkSet = new JWKSet(rsaKey); return new ImmutableJWKSet<>(jwkSet); } private static KeyPair generateRsaKey() { KeyPair keyPair; try { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(2048); keyPair = keyPairGenerator.generateKeyPair(); } catch (Exception ex) { throw new IllegalStateException(ex); } return keyPair; } @Bean public JwtDecoder jwtDecoder(JWKSource<SecurityContext> jwkSource) { return OAuth2AuthorizationServerConfiguration.jwtDecoder(jwkSource); } @Bean public PasswordEncoder encoder() { return new BCryptPasswordEncoder(); } 위 코드로 진행했을 시 발생하는 Cors Error입니다 Access to XMLHttpRequest at 'http://localhost:6080/oauth2/authorize?client_id=oidc-client&redirect_uri=https%3A%2F%2Foidcdebugger.com%2Fdebug&scope=openid&response_type=code&response_mode=form_post&state=3it6dl9kewr&nonce=hyq3pnronj7&continue' (redirected from 'http://localhost:6080/login') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. 3. 이로 인해 CorsFilter를 적용하게 되면 해당 Cors는 해결되지만 authorization code 가 Redirect되는 시점에 Cors 에러가 새롭게 나옵니다. CorsFilter @Component @Slf4j @Order(Ordered.HIGHEST_PRECEDENCE) public class CorsFilter implements Filter { private static final Set<String> allowedOrigins = new HashSet<String>(); static { allowedOrigins.add( "http://localhost:3000" ); } @Override public void init(FilterConfig fc) throws ServletException { } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; HttpServletRequest request = (HttpServletRequest) req; String origin = request.getHeader(HttpHeaders.ORIGIN); log.info("Origin: {}", origin); if (origin != null) { Optional<String> first = allowedOrigins.stream().filter(origin::startsWith).findFirst(); first.ifPresent(s -> response.setHeader("Access-Control-Allow-Origin", s)); } response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Methods", "*"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Key, Authorization"); if ("OPTIONS".equalsIgnoreCase(request.getMethod())) { response.setStatus(HttpServletResponse.SC_OK); } else { chain.doFilter(req, res); } } @Override public void destroy() { } Cors 오류 Access to XMLHttpRequest at 'https://oidcdebugger.com/debug?code=1o_jSQQVu6EB4XDq-xCWP3qrzp2VDdGbH_AN7iBJGU5gQRC7BRFkQYdn2A6P-6G5Aoi8XLJLaVR4MSVktNzDvYLMmj_UXahcWfEwQdA-tk4GCw5Bff4mXn2q6mIYfs_d&state=3it6dl9kewr' (redirected from 'http://localhost:6080/login') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. 혹시 외부 로그인 페이지와 연동한 예시가 있거나, Cors 문제를 해결할 방안이 있는지 궁금합니다ㅠㅠ
java spring spring-boot oauth react
2023-11-02T06:01:48.590Z
댓글 2
좋아요 0
조회수 830
미해결
[개정판] 파이썬 머신러닝 완벽 가이드
안녕하세요, 선생님. 강의 15분 경에 다음과 같은 코드가 나옵니다만, 저는 분명 동일한 코드를 실행했는데 오류가 떠서 질문드립니다. house_df.fillna(house_df.mean(),inplace = True) TypeError: can only concatenate str (not "int") to str 이 코드가 Null있는 문자형 열까지 포함시켜 처리하기 때문에 오류가 나는 거 같은데, 혹시 원래 정상적으로 실행되는 코드인가요…? 책에 있는 코드도 동일한데 제가 실행시키면 에러가 나서 전 Null 있는 숫자혀여 열에 대해서만 각 열의 평균값으로 결측치를 채워서 실행했습니다. 만약 현재 버젼으로 정상적으로 실행이 되지 않는 코드라면 선생님께서 혹시 이 부분에 대해서만 새로 작성하신 코드를 여쭙고 싶습니다! 방금 확인해보니까 jupyter notebook으로는 잘 실행되는데, vscode에서는 위와 같은 오류가 뜹니다. 혹시 이 오류가 뜨는 이유를 알 수 있을까요?
맹고
2023-11-02T05:01:27.183Z
댓글 1
좋아요 0
조회수 590
해결됨
[리뉴얼] React로 NodeBird SNS 만들기
강좌에서처럼 me(내 정보 불러오는 상태변수) 변수를 통해 로그인 유지를 하고 특정 페이지에서 비로그인 사용자를 차단할경우 useEffect(() => { if(!me){ redirects(); } },[]) 이런식으로 로직을 짤수가 있는데 문제가 브라우저 url로 접속할 경우 초기 me 의 상태가 null 이기 때문에 로그인을 한 상태더라도 리다이렉트가 되는 문제가 있었습니다. 물론 ssr을 이용하면 이 문제가 해결은 되지만 csr만 이용하는 선에서 리다이렉트가 정상적으로 작동하도록 하고 싶은데 어떻게 하면 좋을까요?
react redux node.js express next.js
kenny
2023-11-02T00:23:01.273Z
댓글 1
좋아요 0
조회수 369
해결됨
[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
안녕하세요 저작권 관련 질문드립니다! 본 학습 자료의 저작권은 코드캠프에 있어 무단 도용, 배포, 복제를 금지한다고 적혀있는데 그럼 혹시 개인 블로그에 내용을 공부한 내용을 정리한 것을 공개 처리해두어도 문제가 되지 않을지 문의드립니다.
react node.js seo graphql next.js
lumpyspaceyz
2023-11-01T07:49:25.874Z
댓글 1
좋아요 0
조회수 368