forked from node-fetch/node-fetch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example.js
37 lines (26 loc) · 907 Bytes
/
example.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/*
Here are some example ways in which you can use node-fetch. Test each code fragment separately so that you don't get errors related to constant reassigning, etc.
Top-level `await` support is required.
*/
import fetch from 'node-fetch';
// Plain text or HTML
const response = await fetch('https://github.com/');
const body = await response.text();
console.log(body);
// JSON
const response = await fetch('https://github.com/');
const json = await response.json();
console.log(json);
// Simple Post
const response = await fetch('https://httpbin.org/post', {method: 'POST', body: 'a=1'});
const json = await response.json();
console.log(json);
// Post with JSON
const body = {a: 1};
const response = await fetch('https://httpbin.org/post', {
method: 'post',
body: JSON.stringify(body),
headers: {'Content-Type': 'application/json'}
});
const json = await response.json();
console.log(json);