Javascript 및 PHP에서 HTTP 요청을 하려면 어떻게 해야 합니까?

Dec 15 2022
JavaScript에서 HTTP 요청을 하려면 XMLHttpRequest 개체 또는 최신 가져오기 API를 사용할 수 있습니다. 다음은 XMLHttpRequest를 사용하는 예입니다. 가져오기 API는 최신 브라우저에서만 지원되므로 polyfill을 사용하거나 이전 브라우저의 경우 XMLHttpRequest를 사용하도록 대체해야 할 수 있습니다.

JavaScript에서 HTTP 요청을 만들려면 XMLHttpRequest개체 또는 최신 fetchAPI를 사용할 수 있습니다.

다음은 다음을 사용하는 예입니다 XMLHttpRequest.

var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://www.example.com/', true);

xhr.onload = function() {
  if (this.status == 200) {
    var data = JSON.parse(this.response);
    console.log(data);
  }
};

xhr.send();

fetch('https://www.example.com/')
  .then(response => response.json())
  .then(data => console.log(data));

API 는 최신 브라우저에서만 지원되므로 polyfill을 사용하거나 이전 브라우저 fetch를 사용하도록 폴백해야 할 수 있습니다 .XMLHttpRequest

그리고 PHP에서 HTTP 요청을 하려면 내장 함수 file_get_contents() 또는 더 강력한 cURL 라이브러리를 사용할 수 있습니다.

file_get_contents() 사용:

<?php
  // Set the URL of the request
  $url = 'http://www.example.com';
  
  // Send the request and store the response
  $response = file_get_contents($url);
  
  // Check for errors
  if($response === false) {
    // Handle error
  } else {
    // Use the response
  }
?>

<?php 
    // Initialize cURL
    $ch = curl_init();
    
    // Set the URL of the request
    curl_setopt($ch, CURLOPT_URL, 'http://www.example.com');
    
    // Set cURL options
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the response as a string
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Follow redirects
    
    // Send the request and store the response
    $response = curl_exec($ch);
    
    // Check for errors
    if(curl_errno($ch)) {
      // Handle error
    } else {
      // Use the response
    }
    
    // Close the cURL handle
    curl_close($ch);
?>