나는 그 동안 다른 프로젝트로 django로 앱 서버 구현하기(rest api)를 했었는데, 이번에 express로 앱 서버를 구현하게 되었다. 부담감이 하늘을 치솟을 정도라 며칠간 간만 본 express 공부를 제대로 하고자 이 포스팅을 작성하게 되었다.
package.json에 적혀 있는 dependency 대로, npm install
만 terminal에 치면 나머지는 다 install이 되는 듯하다.
(실험 요함)
es6을 지원해준다는 이유로 babel을 깔게 하는 듯하다.
require()에서 import from 문법으로 바뀐다는 차이인데, 익숙한 건 import from이나, 굳이 babel까지 배워야 한다는 생각이 들어 babel은 과감히 빼도록 할 것이다.
어떤 곳에서는 express 어느 버전 이상이면 body-parser를 쓰지 않고 express를 쓰는 걸 권장한다고 하는데, 왜 나는 express를 쓰면 http request가 잘 작동하지 않는 지에 관하여 궁금하였다.
그래서 알아본 결과,
(https://medium.com/@mmajdanski/express-body-parser-and-why-may-not-need-it-335803cd048c)
express 버전 4.16 이상부터 body-parser를 express 자체에 통합했다고 한다. 그래서 기존
app.use(bodyparser.json());
app.use(bodyParser.urlencoded({extended: true}));
과 달리,
app.use(express.json());
app.use(express.urlencoded());
이렇게 작성하는 걸 권장한다고 한다.
body-parser 기능의 대부분이 express에 잘 구현이 되었지만, 특수한 기능의 경우 구현이 안 되어 있을 수도 있다.
(구현이 안 된 특수한 기능은 다음번에 포스트하겠다.)
해당 내용은 아래 출처 링크의 영상을 3번을 돌려보고 해석하고 따라 쓴 글입니다.
출처: https://www.youtube.com/watch?v=tvAgdXMVx9s
https://www.youtube.com/watch?v=7nafaH9SddU
보면서 JWT token 더 알아보기
원래 token authentication에서는,
즉 nodejs(express) - web browser 간의 token authentication에서는,
esktop clients가 cookies를 사용해서 authentication을 진행한다.
react native에서는 이 문제를 custom fetch wrapper for RN이라는 방법을 이용하여 해결할 수 있다.
그래서 react native에서 how to handle cookies, session management 등에 대해 알아보자.
// react native에서 custom fetch wrapper 구현한 것
import AsyncStorage from "@react-native-community/async-storage'
export default async function _fetch(url, config) {
let token;
try {
token = await AsyncStorage.getItem('authToken');
// check if I have the auth token
const body = config && config.body || null;
const headers = config && config.headers || {};
const configObject = {
...config,
credentials: "omit",
headers: {
...headers,
'X-Requested-With': 'app',
'X-Access-Token': String(token),
// In the server middleware, if 'X-Access-Token' exists, the middleware replace this with the cookie.
'Cookie': null
},
body: JSON.stringify(body)
}
// more manipulation
return fetch(url, configObject);
} catch (error) {
console.log('Unauthenticated request');
}
서버 미들웨어에서도 req가 들어왔을 때 해 줘야 하는 일이 있는데,
이는
// middleware for server
function auth(req, res, next){
// auth는 모든 routes에 대한 미들웨어에 해당한다.
// express가 session을 parse하기 전에 해당 미들웨어가 있어야 한다는 점 명심.
const value = req.headers['x-access-token'];
if (!value) {
// not authenticated
// OR
// normal browser user
return next();
}
// manually inject the cookie: sid=default node cookie standard
req.headers.cookie = `connect.sid=s%3A${value};`
next()
}
이것이다.
이때, jwt access token을 사용한 게 맞는 지, 혹은 user custom token 방식을 사용한 건 지 궁금한데(이건 영상을 다시 봐야 알 것 같다)...