How to send http request via javascript

JavaScript is a widely used programming language that can be used to create rich Internet applications. One of the common tasks is to communicate with backend servers to get or send data. In this article, we'll discuss how to send HTTP requests using JavaScript. We'll describe how to do this using XMLHttpRequest and the fetch API, with some sample code and best practice advice.

XMLHttpRequest

XMLHttpRequest is a primitive way of sending HTTP requests using JavaScript, which allows you to asynchronously fetch data from the browser without refreshing the page. This allows you to respond more quickly to user actions and dynamically update content without reloading the entire page.

Send a GET request

To send a GET request, you create a new XMLHttpRequest object, set the request's method and URL, and open the request with the open() method. You can then send the request using the send() method.

Here's a simple example that uses XMLHttpRequest to send a GET request:

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/users');
xhr.onload = () => {
  if (xhr.status === 200) {
    console.log(xhr.responseText);
  } else {
    console.error(`Error: ${xhr.status}`);
  }
};
xhr.send();

In this example, we create a new XMLHttpRequest object and use the open() method to set the method and URL of the request. Then, we define an onload callback function that will be called when the response is received. If the response status is 200, we will print the response text. Otherwise, we print the error message and response status.

Send a POST request

To send a POST request, you need to set the headers and body. The request header specifies the type of data to be sent, and the request body contains the actual data. Here is an example of sending a POST request using XMLHttpRequest:

const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://jsonplaceholder.typicode.com/users');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = () => {
  if (xhr.status === 201) {
    console.log(xhr.responseText);
  } else {
    console.error(`Error: ${xhr.status}`);
  }
};
xhr.send(JSON.stringify({
  name: 'John Doe',
  email: '[email protected]',
}));

In this example, we use the open() method to set the method and URL of the request, and the setRequestHeader() method to set the request headers. We also define an onload callback function to handle when the response is received. When sending a request, we convert the JavaScript object to a JSON string and send it as the request body using the send() method.

Fetch API

The Fetch API is a new way that provides a simpler, more readable syntax for sending HTTP requests. Unlike XMLHttpRequest, the fetch API is Promise-based, which means you can handle asynchronous operations more easily and use less code to perform the same task.

Send a GET request

To send a GET request, you can use the fetch() method, which accepts the URL to fetch as a parameter. fetch() returns a Promise, and you can use its then() method to handle the response.

Here's a simple example that uses the fetch API to send a GET request:

fetch('https://jsonplaceholder.typicode.com/users')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

In this example, we use the fetch() method to send a GET request and handle the response in the then() method. The first then() method converts the response object into JSON format and passes it as a parameter to the next then() method. In the second then() method, we print the JSON data to the console. If an error occurs, we catch it using the catch() method and print an error message.

Send a POST request

To send a POST request, you use the fetch() method and specify the method, headers, and body attributes in the request. As with XMLHttpRequest, the headers attribute specifies the type of data to be sent, and the body attribute contains the actual data.

Here is an example of sending a POST request using the fetch API:

fetch('https://jsonplaceholder.typicode.com/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'John Doe',
    email: '[email protected]',
  })
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

In this example, we use the fetch() method to send a POST request and specify the method, headers, and body attributes in the request. In the then() method, we convert the response object into JSON format and pass it as a parameter to the next then() method. In the second then() method, we print the JSON data to the console. If an error occurs, we catch it using the catch() method and print an error message.

best practice advice

Note the following best practices when sending HTTP requests:

  • Make sure to validate user input before sending the request. This prevents malicious users from exploiting your application to send unwanted data.

  • When using XMLHttpRequest, be sure to define onload and onerror callback functions. This can help you better handle responses and errors.

  • When using the fetch API, make sure to use the catch() method to catch errors and print error messages to the console. This can help you debug and fix bugs better.

  • When sending a POST request, make sure to set the correct Content-Type header and use the correct data format.

  • Finally, make sure to send the request using the HTTPS protocol. This ensures your data is encrypted in transit and prevents malicious users from stealing your data.

in conclusion

In this article, we covered how to send HTTP requests using JavaScript. We explored both approaches using XMLHttpRequest and the fetch API, and provided some sample code and best practice advice. By using these methods, you can respond more quickly to user actions and communicate with backend servers to get or send data.

Besides that, you can use other libraries and frameworks to send HTTP requests. For example, jQuery provides a convenient ajax() method to easily send GET, POST, PUT, DELETE, etc. requests. Axios is another popular HTTP client library that provides more features and configuration options like interceptors, cancel requests, etc.

Whichever method you use, you should follow best practices to ensure that the requests you send are safe and correct, and that responses and errors are handled successfully.

Hope this article can help you better understand how to use JavaScript to send HTTP requests, and provide you with some guidance for handling requests in actual development.

Guess you like

Origin blog.csdn.net/tyxjolin/article/details/130349357