Node.js를 사용하여 데이터를 가져오기 위해 HTTP 요청 수행

오늘의 기사에서는 HTTP 요청을 만들고 node.js를 사용하여 데이터를 가져오는 방법을 배웁니다.
Node.js를 사용하여 데이터를 가져오기 위한 HTTP 요청
node.js의 내장 모듈을 사용하여 HTTP 요청을 보낼 수 있습니다. 콜백은 이러한 표준 모듈에서 요청을 처리하고 데이터를 얻는 데 사용됩니다.
Axios
, node-fetch
, super agent
및 기타 모듈을 사용하여 HTTP 요청을 보낼 수도 있습니다. HTTPs 모듈은 request
기능을 사용하여 호출합니다.
서버 URL의 호스트 이름
, 포트
번호 및 경로
와 요청 종류를 제공하는 옵션 개체가 이 요청 함수에 인수로 전달됩니다.
callback
함수는 두 번째 인수입니다. 요청이 처리되면 이 콜백
기능이 활성화됩니다. HTTPs 모듈에는 요청을 처리하고 요청된 데이터를 가져올 수 있는 여러 이벤트가 있습니다.
예를 들어 요청을 종료하려면 오류 발생 시 req.end()
및 req.on('error')
를 사용하십시오. 요청을 받은 후 서버는 데이터를 처리하고 청크로 응답을 다시 보냅니다.
res.on('data')
또는 res.on('end')
와 같은 응답 관련 이벤트가 발생하면 응답을 검색할 수 있습니다. end 이벤트에서 전체 응답이 반환되면 data 이벤트에서 데이터 청크를 연결한 후 콘솔에 출력할 수 있습니다.
https.request
는 비동기
이므로 요청이 완료되기 전에 서버 응답을 읽으려고 시도하면 정의되지 않은 반환됩니다. 아래의 간단한 예를 통해 위의 프로세스를 이해해 봅시다.
예제 코드:
const https = require('https');
const options = {
hostname: 'jsonplaceholder.typicode.com',
port: 443,
path: '/posts/1',
method: 'GET',
};
function submitRequest() {
const req = https.request(options, res => {
let outputData = ''
console.log(`statusCode: ${res.statusCode}`);
res.on('data', dataChunk => {
outputData += dataChunk;
});
res.on('end', () => {
console.log('outputData', outputData);
});
});
req.on('error', error => {
console.error('error', error);
});
req.end();
}
submitRequest()
위의 코드 예제에서는 path
및 port
번호를 지정하여 모의 서버에 GET
요청을 보냅니다. 요청을 받고 데이터를 처리한 후 서버는 응답을 분할하여 다시 보냅니다.
end 메서드에서 응답이 완전히 반환되면 응답 데이터를 연결하고 콘솔에 출력할 수 있습니다.
node.js와 호환되는 Replit
에서 위의 코드 줄을 실행합니다. 다음과 같은 결과가 표시됩니다. 위 코드에 대한 데모도 여기에서 찾을 수 있습니다.
출력:
statusCode: 200
outputData {
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
Shraddha is a JavaScript nerd that utilises it for everything from experimenting to assisting individuals and businesses with day-to-day operations and business growth. She is a writer, chef, and computer programmer. As a senior MEAN/MERN stack developer and project manager with more than 4 years of experience in this sector, she now handles multiple projects. She has been producing technical writing for at least a year and a half. She enjoys coming up with fresh, innovative ideas.
LinkedIn