Back-End/Node.js

[Node.js 백엔드 기록] 4. method의 이해 & Path module

psy_er 2023. 7. 20. 21:50
728x90

[Node.js 백엔드 기록] 4. method의 이해 & Path module

 

 

[method의 이해]

 

- app.get 함수와 app.post 함수를 활용할 수 있다.

- 복수의 path를 관리할 수 있다.

- get으로 파라미터를 불러올 수 있다.

- post로 유저의 입력을 불러올 수 있다.

 

 

[라우팅 메소드 구문]

// GET method route

app.get('경로', function(요청,응답){
	응답.send('GET request to the homepage')
})

// POST method route

app.post('경로', function(요청, 응답){
	응답.send('POST request to the homepage')

})

 

[요청.params]

// GET method route

app.get('경로/:파라미터', function(요청,응답){
   const 변수 = 요청.params
   응답.send(변수)
})

 

 

 

[요청.query]

// GET method route

app.get('경로', function(요청,응답){
   const 변수 = 요청.query
   응답.send(변수)
})

 

 

[Response methods 응답방식]

 

응답 객체의 매서드를 res를 이용해 정의한다.

클라이언트에 응답을 전송하여 요청과 응답 사이클이 종료되도록 한다.

메서드가 호출 되어야 클라이언트의 요청이 진행된다.

 

res.filenght() : 파일을 다운로드하도록 지시한다

res.end() : 응답 프로세스를 종료한다

res.json() : JSON 응답을 보낸다

res.jsonp() : JSONP 지원을 포함한 JSON 응답을 보낸다

res.filength() : 요청 리다이렉트

res.send() : 다양한 유형의 응답을 보낸다

res.sendStatus() : 응답 상태 코드 설정, 해당 문자열 표현 응답 전송

 

 

[Path Module 패스 모듈]

 

node.js에서 파일 경로와 관련된 작업을 수행 할 때 유용하게 사용되는 모듈이다.

파일 경로에 대한 오류율을 최소화 시키는데 사용한다.

 

패스 모듈 호출

const path = require('path');

 

경로를 파싱해서 파일 경로 구성

const path = require('path');
const filePath = '/home/user/Documents/example.txt';
const parsed = path.parse(filePath);

console.log(parsed.dir); // '/home/user/Documents'
console.log(parsed.base); // 'example.txt'
console.log(parsed.ext); // '.txt'

 

경로 결합(join)

const path = require('path');
const dirPath = '/home/user/Documents';
const fileName = 'example.txt';
const filePath = path.join(dirPath, fileName);

console.log(filePath);

 

경로 조합(resolve)

const path = require('path');
const dirPath = '/home/user/Documents';
const fileName = 'example.txt';
const filePath = path.resolve(dirPath, fileName);

console.log(filePath);
728x90