• 로그인
  • 장바구니에 상품이 없습니다.

home2 게시판 Node.js, Express 게시판 질문을 다시 정리해서 왔습니다 하하

질문을 다시 정리해서 왔습니다 하하

4 글 보임 - 1 에서 4 까지 (총 4 중에서)
  • 글쓴이
  • #110034

    김준기
    참가자
    로그인 문제 하나는 해결을 했는데 하나는 도저히 원인을 모르겟습니다..
    
    우선 로그인 페이지에서 post 요청을 합니다.
    로그인 페이지
        <Container>
          <Row className="mt-5">
            <Col></Col>
            <Col>
              {" "}
              <Form action="http://localhost:8080/login" method="POST">
                <Form.Group className="mb-3" controlId="exampleForm.ControlInput1">
                  <Form.Label>ID</Form.Label>
                  <Form.Control type="text" name="id" />
                </Form.Group>
                <Form.Group className="mb-3" controlId="formBasicPassword">
                  <Form.Label>Password</Form.Label>
                  <Form.Control type="password" name="pw" />
                </Form.Group>
                <Button variant="primary" type="submit">
                  Log In
                </Button>
              </Form>
            </Col>
            <Col></Col>
          </Row>
        </Container>
    
    서버에서 post 요청을 받으면 요청.user가 서버 콘솔에 정상적으로 나오고 http://localhost:3000로 redirect를 합니다.
    서버 사이드
    app.post(
      "/login",
      passport.authenticate("local", {
        failureRedirect: "http://localhost:3000/fail",
      }),
      function (요청, 응답) {
        const userData = 요청.user;
        console.log(userData)
        응답.redirect("http://localhost:3000");
      }
    );
    
    http://localhost:3000로 redirect 되었을 때 서버 콘솔에 찍히는 userData를 프론트에서 사용하고 싶어서 다음과 같이 fetch를 했는데,
    브라우저 콘솔에서는 console.error로 응답이 뜹니다. 서버 콘솔에서 이미 userData를 출력했는데, redirect한 페이지에서는 
    왜 userData를 바로 받지 못하는 걸까요? 
    http://localhost:3000의 navbar
      fetch("http://localhost:8080/session", {
        method: "GET",
        credentials: "include", 
      })
        .then(response => {
          if (response.ok) {
            return response.json();
          } else {
            throw new Error("Not a JSON response");
          }
        })
        .then(data => {
          console.log(data.user);
          setIsLoggedIn(!!data.user);
        })
        .catch(error => {
          console.error("Error fetching mypage:", error);
          setIsLoggedIn(false);
        });
     
    #110055

    codingapple
    키 마스터
    서버의 /session API에서 보내는 데이터가 뭔가 이상한게 아닐까요 
    아니면 에러코드는 뭐뜨나 출력해봅시다
    #110057

    김준기
    참가자
    그런데 redirect 이후에 다른 페이지를 클릭하면 데이터가 브라우저 콘솔에 또 뜹니다! 환장하겠네요 ㅠㅠ
    프론트는 위에서 살짝 수정했습니다.
    http://localhost:3000의 navbar
    
      fetch("http://localhost:8080/session", { -----------------http://localhost:8080/session net::ERR_FAILED 200 (OK)
        method: "GET",
        credentials: "include", 
      })
        .then(response => {
          if (response.ok) {
            return response.json();
          } else {
            throw new Error("Not a JSON response");
          }
        })
        .then(data => {
          console.log(data.user);
          setIsLoggedIn(!!data.user);
        })
        .catch(error => {
          console.error("Error fetching mypage:", error); -----------------Error fetching mypage: TypeError: Failed to fetch
          setIsLoggedIn(false);
        });
    
    #110093

    codingapple
    키 마스터
    localhost:8080말고 127.0.0.1:8080으로 요청해봅시다
    근데 리액트쓰면 애초에 폼태그로 폼전송하진않습니다 state초기화되고 단점이 많아서
    ajax로 로그인시키고 그 결과 받아오는게 나을듯요
4 글 보임 - 1 에서 4 까지 (총 4 중에서)
  • 답변은 로그인 후 가능합니다.

About

현재 월 700명 신규수강중입니다.

  (09:00~20:00) 빠른 상담은 카톡 플러스친구 코딩애플 (링크)
  admin@codingapple.com
  이용약관
ⓒ Codingapple, 강의 예제, 영상 복제 금지
top

© Codingapple, All rights reserved. 슈퍼로켓 에듀케이션 / 서울특별시 강동구 고덕로 19길 30 / 사업자등록번호 : 212-26-14752 온라인 교육학원업 / 통신판매업신고번호 : 제 2017-서울강동-0002 호 / 개인정보관리자 : 박종흠