NodeJS에서 파라미터를 받아볼게요.
http 통신에 대한 기초적인 개념이 있으셔야 하구요.
1. 파라미터 받기 (Parameter)
http://localhost:3000/users?userId=gofnrk&password=1234
요런식으로 파라미터를 전송해볼게요.
router.get('/', function(req, res, next) {
let { userId, password } = req.query;
console.log(userId);
console.log(password);
res.send('respond with a resource');
});
2. 경로를 변수로 받기 (Path Variable)
http://localhost:3000/users/gofnrk
요렇게 호출했을 때 gofnrk가 고정 경로가 아닌 변수로서 사용하고 싶네요.
router.get('/:userId', function(req, res, next) {
let { userId } = req.params;
console.log(userId);
res.send('respond with a resource');
});
3. Body로 받기
POST 방식으로 Body에 데이터를 담아서 json 형태로 보내고 NodeJS에서 받아볼게요.
저는 Postman 툴을 이용해서 보낼거에요.
router.post('/', function(req, res, next) {
let { userId, password } = req.body;
console.log(userId);
console.log(password);
res.send('respond with a resource');
});
4. Header 정보 받기
이번엔 헤더 정보를 받아볼게요.
주의해야 할 점은 코드 상에서 헤더명을 모두 소문자로 치환해서 적어줘야된다는 점!
죄송하게도.. 구체적으로 알아보진 않았지만 내부적으로 치환하는 것 같아요.
router.get('/', function(req, res, next) {
let headerName = req.headers["header-name"];
console.log(headerName);
res.send('respond with a resource');
});
위에 내용만 제대로 사용할 줄 알아도 프론트에서 기본적인 텍스트 정보를 전달 받는데는 어려움이 없을거에요.
'Backend > Node.js' 카테고리의 다른 글
Node.js Logging 설정 (winston) (0) | 2020.09.04 |
---|---|
Node.js exception handler - custom error (0) | 2020.09.04 |
Node.js 재시작 없이 반영, 자동 재시작 (Supervisor) (0) | 2020.04.01 |
Node.js 코딩 패턴 (Routes-Controllers-Services 구조) (2) | 2019.11.13 |
Node.js MySQL Transaction(트랜잭션) (6) | 2019.11.13 |