You can use the Fetch API to send a request directly in Node.
fetch('https://link-to-resource') .then(response => response.json()) .then(data => console.log(data))Node supports Fetch natively since v17.0.0. If you’re using an earlier
version of Node, you’ll need to install libraries like node-fetch to use
Fetch in Node.
You can also use a library like zlFetch too. (More on this below).
CORS restrictions don’t apply on servers
Earlier in the course, I demonstrated the fact that you can’t use XHR or Fetch on some servers because of CORS.
Well, these CORS restrictions don’t apply when you send the same request through a server. For example, you can fetch google.com and get the HTML as a response back from the server.
fetch('https://google.com') .then(response => response.text()) .then(data => console.log(data))
https://google.com Installing zlFetch
You can install zlFetch with npm.
To do this, go to your command line, navigate to the project folder, and type the following command:
npm install zl-fetch -SThe -S flag saves zl-fetch as a dependency. We do this because we will use
zlFetch in the production code.
When the command is done, you will see a node_modules folder in your project. Inside this node_modules folder, you will be able to find zl-fetch.
This is how you know the library has been installed.
Using the zlFetch library
You must import a library into your file before you can use it.
import zlFetch from 'zl-fetch'Once you do this, you can use zlFetch.
zlFetch('https://api.github.com/users/zellwk/repos') .then(response => { const repos = response.body console.log(repos) })If you run the server now, you should see a huge list of content in your Terminal.
This happens because the Terminal does not have interactive functions, unlike browser consoles — you can’t click on the dropdown to view the object, so it simply displays everything when it can.
If you want to get a log that seems less insane, you need to be intentional about what you’re trying to log. For example, you can log the length of the array if you want to know how many items there are.
zlFetch('https://api.github.com/users/zellwk/repos').then(response => { const repos = response.body console.log(repos.length)})
That’s all you need to know about sending requests with Node.
There’s one final thing for you to know in this chapter — how to protect your API Keys and API Secrets so they’re safe from prying eyes.
Welcome! Unfortunately, you don’t have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson