1

I am recently learning how to code on Udemy, and I encountered a problem. when we fetch API we can fetch from the browser and we can also use node-fetch from node.js. I want to know what's the difference between them. Can we directly fetch API from external server not through the web server.if so what should we fetch data from node.js?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Peter Li
  • 21
  • 1
  • 3

2 Answers2

4

Node.js does not come with the fetch libriary per default. Fetch API does only exist in webbrowsers under window.fetch. Node-fetch is just a lightweight libriary containing this webbrowser fetch.

That said to install and use fetch in Node.js use following commands:

npm i node-fetch

Then to import it use

import fetch from 'node-fetch';

See the official npm package of node-fetch.

The Fetch API is very basic. If you have to use Http Requests in a Node.js app I would recommend using axios.

Flashtube
  • 209
  • 1
  • 6
1

We can try to fetch the external API from the browser. That can give Cross Origin Resource Sharing (CORS) errors if the endpoint does not want you to access their API from a browser

Then you can write a proxy that accesses the external API from the server, that will be allowed regardless of CORS settings

So accessing an API from NODE will always work (assuming no need for authentication) and fetch from browser may or may not work directly.

NOTE: node-fetch is not native to node

mplungjan
  • 169,008
  • 28
  • 173
  • 236