[node.js] MERN stacks 기본

Suyeon·2021년 6월 8일
2

Node.js

목록 보기
4/4
post-thumbnail

Node.js

.env 파일 사용하기

  • npm i dotenv
// (1) Create config.js
require('dotenv').config({
  path: '/Users/suyeonkang/playground/cake-factory/.env', // (*) path should be corresponded!
});

module.exports = {
  mongodbUrl: process.env.MONGODB_URL,
  port: process.env.PORT,
};

// (2) Use
const { port, mongodbUrl } = require('../config/config');

CORS 핸들링하기

express를 사용하는 경우, 방법은 크게 두가지가 있다.

  • cors 라이브러리 사용
  • middleware에 추가
// (1) cors 라이브러리 사용
const cors = require('cors');

app.post('/suyeon', cors(), (req, res) => {
  res.send('cors!');
});

// (2) middlewared에 직접 추가
app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8000');
  res.setHeader(
    'Access-Control-Allow-Methods',
    'GET, POST, OPTIONS, PUT, PATCH, DELETE'
  );
  res.setHeader(
    'Access-Control-Allow-Headers',
    'X-Requested-With,content-type'
  );
  res.setHeader('Access-Control-Allow-Credentials', true);
  next();
});

// (3) middleware에 cors라이브러리 적용 💫
app.use(cors());

Middleware

express에서 cookie 관리(추출)를 쉽게 도와주는 미들웨어이다. req, rescookies object가 부여된다.

const cookieParser = require('cookie-parser');

app.use(cookieParser());

// req
app.get('/', (req, res) => {
    console.log('cookies: ', req.cookies)
})

// res
res.cookie('hasVisited', '1', {
    maxAge: 60*60*1000,
    httpOnly: true,
    path:'/visited'
});

Options

  • maxAge : 만료 시간을 밀리초(ms) 단위로 설정
  • expires : 만료 날짜를 GMT 시간으로 설정
  • path : cookie의 경로
  • domain : 도메인 이름
  • secure : https에서만 cookie를 사용할 수 있도록 허용
  • httpOnly : http를 통해서만 cookie 접근할 수 있도록 허용

CRA

create-react-appnode.js 함께 사용하기

Proxy


만약 서버를 port 3000에서 돌리고 있다면, 아래와 같이 해당 서버를 proxy로 추가한다. proxy를 추가할경우, 클라이언트에서 보내는 /api는 프록시 서버로 redirect된다.

  • 이유는 모르겠으나, 간혹 proxy request fail 에러가 떴는데 http://localhost:3000http://127.0.0.1:3000로 수정하니까 해결됬다.

  "scripts": {
    "start": "react-scripts start",
	// ...
  },
  "proxy": "http://127.0.0.1:3000",

클라이언트에서 request를 보낼때는 localhost:3000을 제외한 /endpoint
를 보낸다.

fetch('/post')

Protected Route

로그인 여부(authentication)에 따라서 protected route 적용하기

const ProtectedRoute: React.FC<{
  component: React.FC;
  path: string;
  exact: boolean;
  isAuth: boolean;
}> = props => {
  const { path, exact, component, isAuth } = props;

  if (isAuth) {
    return <Route path={path} exact={exact} component={component} />;
  }
  return <Redirect to="/signin" />;
};

// Using
  return (
      <Router>
        <Switch>
          <Route path="/signin" exact={true} component={Signin} />
          <Route path="/signup" exact={true} component={Signup} />
          <PrivateRoute
            path="/collection"
            exact={true}
            component={CakeCollection}
            isAuth={isAuth}
          />
          <Route component={PageNotFound} />
        </Switch>
      </Router>
  );
profile
Hello World.

0개의 댓글