• 카테고리

    질문 & 답변
  • 세부 분야

    풀스택

  • 해결 여부

    해결됨

Credentials 설정 후 origin: true를 줘도 헤더 결과값이 안들어가요

23.03.18 10:35 작성 조회수 464

0

안녕하세요!

Credentials 설정 후 origin을 'http://localhost:3060' 으로도, true 로도 변경해봤지만 계속해서 해당 오류가 뜨는데 이유를 모르겠습니다. ㅠㅠ

제로초님의 오류와 다른 부분이 있는 것 같습니다.

Access to XMLHttpRequest at 'http://localhost:3065/user/login' from origin 'http://localhost:3060' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

제 코드는 현재 이렇습니다.

[app.js]

const express = require("express");
const session = require("express-session");
const cookieParser = require("cookie-parser");
const cors = require("cors");
const passport = require("passport");
const dotenv = require("dotenv");
const postRouter = require("./routes/post");
const userRouter = require("./routes/user");
const db = require("./models");
const passportConfig = require("./passport");
const app = express();

dotenv.config();
passportConfig();

//서버 실행할 때 db sequelize 연결도 함께 실행
db.sequelize
  .sync()
  .then(() => {
    console.log("db 연결 성공");
  })
  .catch(console.error);

// router보다 위에 작성해야 함
app.use(
  cors({
    // origin: 'https://nodebird.com' // 설정된 웹페이지에서 오는 요청만 허용
    // origin: "*" // 전체 허용
    // origin: "http://localhost:3060", // withCredential: true 일 때 보안이 더 철저해져서 정확한 주소를 적어야 함
    origin: true, // 요청을 보낸 곳의 주소가 자동으로 들어가 허용
    credientials: true,
  })
); // CORS 에러 처리법 2 (npm i cors)
app.use(express.json()); // front에서 json형식으로 데이터를 보냈을 때 json형식의 데이터를 req.body로 넣어줌
app.use(express.urlencoded({ extended: true })); // form을 submit했을 때 urlencoded 방식으로 데이터가 넘어옴
app.use(cookieParser(process.env.COOKIE_SECRET));
app.use(
  session({
    saveUninitialized: false,
    resave: false,
    secret: process.env.COOKIE_SECRET,
  })
);
app.use(passport.initialize());
app.use(passport.session());

app.get("/", (req, res) => {
  res.send("hello express");
});

app.get("/posts", (req, res) => {
  res.json([
    { id: 1, content: "hello1" },
    { id: 2, content: "hello2" },
    { id: 3, content: "hello3" },
  ]);
});

app.use("/post", postRouter);
app.use("/user", userRouter);

app.listen(3065, () => {
  console.log("서버 실행중!!!!");
});

[sagas - index.js]

import axios from "axios";
import { all, fork } from "redux-saga/effects";
// take 는 1회용이기 때문에 while(true) {} 문으로 감싸준다. 하지만 직관적이지 않으므로 take 대신에 takeEvery를 사용한다.
// takeLatest 는 클릭이 두번되었을 때 두 번 실행되지 않기 위해 마지막 것만 실행되도록 하는 effect 이다. (요청은 취소되지 않고 응답만 취소되므로 서버에는 두개가 저장됨(치명적단점))
// takeLeading 은 첫번째 것만 실행되도록 하는 effect 이다.
// throttle 은 시간제한을 두어 그 시간동안에 한번만 실행되도록 요청하는 것이다. (특수한 경우에 사용, 디도스 공격을 막을 때 좋음)

import userSaga from "./user";
import postSaga from "./post";

axios.defaults.baseURL = "http://localhost:3065";
axios.defaults.withCredentials = true;

// function* : generator 는 yield(중단점)가 있는 곳에서 멈춤
export default function* rootSaga() {
  // all 은 fork 나 call 을 동시에 실행시켜준다.
  yield all([
    // fork !== call
    // fork 는 비동기 함수 호출 , call 은 동기 함수 호출
    fork(userSaga),
    fork(postSaga),
  ]);
}

어디서 잘못된 걸까요..? 오류를 보면 header in the response is '' 로 헤더의 결과 값이 없는 것같은데...

origin 을 true 로 변경했는데 왜 안들어갈까요...

답변 1

답변을 작성해보세요.

0

credientials 오타입니다. credentials

DDU님의 프로필

DDU

질문자

2023.03.21

앗.... 이런실수를.. 죄송해요 감사합니다