>  기사  >  웹 프론트엔드  >  nodejs http 요청 도구

nodejs http 요청 도구

王林
王林원래의
2023-05-08 19:32:35617검색

Node.js는 매우 인기 있는 개발 환경이며 강력한 JavaScript 엔진은 효율적인 웹 애플리케이션을 제공할 수 있습니다. 웹 개발에서는 HTTP 요청과 응답이 필요한 경우가 많으며, 이를 위해서는 일부 HTTP 요청 도구를 사용해야 합니다. 이 글에서는 Node.js에서 일반적으로 사용되는 HTTP 요청 도구를 주로 소개합니다.

1. Node.js 내장 HTTP 모듈

Node.js에는 HTTP 서비스를 쉽게 생성할 수 있는 기본 HTTP 모듈이 포함되어 있습니다. HTTP 모듈에는 HTTP 요청 헤더 및 요청 본문 읽기, 응답 헤더 및 응답 본문 출력 등을 포함하여 많은 관련 요청 및 응답 API가 제공되므로 사용하기 매우 편리합니다. 다음은 HTTP 모듈을 사용하여 서버를 생성하는 코드입니다.

const http = require('http');

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World!');
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000/');
});

2. 타사 모듈 요청 사용

Node.js에는 HTTP 모듈이 내장되어 있지만 해당 API는 너무 낮은 수준일 수 있으며 사용하기가별로 편리하지 않습니다. 따라서 요청 모듈과 같은 타사 모듈을 사용하도록 선택할 수도 있습니다. 먼저 npm을 사용하여 설치하세요.

npm install request

요청 모듈은 HTTP 요청을 빠르게 완료하고 응답 데이터를 얻을 수 있는 보다 편리한 API를 제공합니다. 다음은 요청 모듈을 사용하여 GET 요청을 보내는 예입니다.

const request = require('request');

request('http://www.baidu.com', function (error, response, body) {
  console.error('error:', error); // Print the error if one occurred
  console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
  console.log('body:', body); // Print the HTML for the Google homepage.
});

3. 타사 모듈 axios를 사용하세요.

요청 모듈 외에도 매우 강력한 HTTP 요청 도구인 axios도 있습니다. 브라우저와 Node.js에서 사용할 수 있는 Promise 기반의 HTTP 클라이언트입니다. axios에는 다음과 같은 기능이 있습니다.

  1. 요청과 응답을 가로챌 수 있습니다.
  2. JSON 데이터를 자동으로 변환합니다.
  3. 취소 요청을 지원합니다.
  4. 기본 요청 헤더와 요청 매개변수를 설정할 수 있습니다.
  5. 더 안정적이고 가벼워졌습니다.

npm을 사용하여 설치:

npm install axios

다음은 axios를 사용하여 GET 요청을 보내는 예입니다.

const axios = require('axios')

axios.get('https://api.github.com/users/johnny4120')
  .then(function (response) {
    console.log(response.data)
  })
  .catch(function (error) {
    console.log(error)
  })

4. 요청 매개변수 처리

요청을 할 때 일부 매개변수를 가져오는 경우가 많으며, 다른 모듈 처리도 있습니다. 방법도 다릅니다. 요청 모듈을 사용하여 요청하는 경우 querystring 모듈을 사용하여 객체를 요청 매개변수 문자열로 변환하거나 json 매개변수를 직접 사용할 수 있습니다. 예:

const querystring = require('querystring');
const request = require('request');

const options = {
  url: 'https://www.google.com/search',
  qs: {
    q: 'node.js'
  }
};

request(options, function(error, response, body) {
  console.log(body);
});

// 或者

request.post({
  url: 'http://www.example.com',
  json: {key: 'value'}
}, function(error, response, body) {
  console.log(body);
});

axios 모듈을 사용할 때 params 매개변수를 사용하여 객체를 쿼리 문자열로 변환하거나 data 매개변수를 사용할 수 있습니다.

const axios = require('axios');

axios.get('https://api.github.com/search/repositories', {
  params: {
    q: 'node',
    sort: 'stars',
    order: 'desc'
  }
})
  .then(function (response) {
    console.log(response.data);
  })
  .catch(function (error) {
    console.log(error);
  });

// 或者

axios.post('http://www.example.com', {foo: 'bar'})
  .then(function (response) {
    console.log(response.data);
  })
  .catch(function (error) {
    console.log(error);
  });

요약하면 다양한 HTTP 요청 도구가 있습니다. Node.js에서 선택하세요. 각각에는 적용 가능한 시나리오가 있습니다. 프로젝트 요구 사항에 따라 가장 적합한 도구를 선택하면 개발이 더욱 효율적이고 편리해집니다.

위 내용은 nodejs http 요청 도구의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.