get external api node js
Install Node.js if you haven't already from the official website.
Create a new directory for your project and navigate into it using the command line.
Run the following command to initialize a new Node.js project:
npm init -y
.Install the
node-fetch
package using the following command:npm install node-fetch
.Create a new JavaScript file, for example
index.js
, and require thenode-fetch
package at the beginning of the file using the following code:const fetch = require('node-fetch');
.Now you can use the
fetch
function to make requests to an external API. For example:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data));
- Remember to handle errors using the
catch
method if the request fails:
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Run your Node.js application using the command
node index.js
and you should see the results from the external API in your console.Remember to replace
'https://api.example.com/data'
with the actual URL of the API you want to fetch data from.