📜  node js fetch - Javascript (1)

📅  最后修改于: 2023-12-03 15:17:53.379000             🧑  作者: Mango

Node.js Fetch - JavaScript

Fetch is a modern interface for making network requests in JavaScript. It provides a more concise and easy-to-use API than the older XMLHttpRequest (XHR) interface. In Node.js, fetch is available as a built-in module called node-fetch. In this article, we will explore how to use Node.js fetch to make HTTP requests in JavaScript.

Installation

To use node-fetch, you need to install it first. You can install it using npm:

npm install node-fetch --save
Basic Usage

Here is an example that shows how to make GET request using node-fetch.

const fetch = require('node-fetch');

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

In the above code, we import the node-fetch module and use the fetch function to make a GET request to the specified URL. We then use the json method to extract the response body as JSON. Finally, we log the returned JSON data to the console.

Making POST Requests

Here is an example that shows how to make a POST request with JSON data using node-fetch.

const fetch = require('node-fetch');

const postData = { title: 'foo', body: 'bar', userId: 1 };

fetch('https://jsonplaceholder.typicode.com/posts', {
    method: 'POST',
    body: JSON.stringify(postData),
    headers: { 'Content-Type': 'application/json' }
  })
  .then(response => response.json())
  .then(json => console.log(json))
  .catch(error => console.error(error));

In the above code, we define the postData object that will be sent as JSON. We then use the fetch function with some configuration options to make a POST request to the specified URL with the JSON data. We also provide the Content-Type header to indicate that the request body is JSON. We then extract the response body as JSON using the json method and log it to the console.

Error Handling

When making network requests, it is important to handle errors properly. In node-fetch, errors are raised as rejected promises. Here is an example that shows how to handle errors using catch.

const fetch = require('node-fetch');

fetch('https://doesnotexist.com')
  .then(response => response.json())
  .then(json => console.log(json))
  .catch(error => console.error(error));

In the above code, we try to make a request to a URL that does not exist. When fetch encounters an error, it raises a rejected promise. We catch this error using catch and log it to the console.

Conclusion

Node.js fetch is a powerful and easy-to-use interface for making network requests in JavaScript. With node-fetch, you can easily make GET, POST, and other types of HTTP requests. It is important to handle errors properly when making network requests, and node-fetch provides a convenient way to do so.