This repository has been archived by the owner on Jan 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfetch.js
executable file
·63 lines (53 loc) · 1.65 KB
/
fetch.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
fetch('test.txt')
.then(function (response) {
console.log(response);
// Um Anhand des Content-Type zu entscheiden, in welchem Format der
// Inhalt weiterverarbeitet wird:
// const contentType = response.headers.get('Content-Type');
// if (contentType.indexOf('text/plain') !== -1) {
// return response.text();
// }
// else (contentType.indexOf('image/jpeg') !== -1) {
// return response.blob();
// }
return response.text();
// Falsch: Der Inhalt dieses Reponse ist vielleicht noch gar nicht vollstaendig
// heruntergeladen worden:
// const body = response.text();
})
.then(function (body) {
console.log(body);
// document.querySelector('main').textContent = body;
});
// Schreibweise mit .then() sind JavaScript Promises
fetch('test.json')
.then(function (response) {
if (response.ok) {
return response.json();
}
})
.then(function (body) {
console.log(body);
document.querySelector('main').textContent = body.message;
});
// Keine Garantie ueber die Reihenfolge von der Antwort von .json oder .txt
const user = {
name: "Neuer User",
age: 33,
hairColor: "red"
};
fetch('api/user', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(user)
})
.then(function (response) {
if (response.ok) {
console.log('User erfolgreich erstellt');
}
else {
console.log('Fehler');
}
});