-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathurlshortener-fetch.js
76 lines (67 loc) · 1.69 KB
/
urlshortener-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
64
65
66
67
68
69
70
71
72
73
74
75
76
// Include data for accessing Google APIs
const apiKey = 'AIzaSyAzCems3-NaPDxmLWMuoPMNiSRyginEmYs';
const url = 'https://www.googleapis.com/urlshortener/v1/url';
// Some page elements
const $inputField = $('#input');
const $expandButton = $('#expand');
const $shortenButton = $('#shorten');
const $responseField = $('#responseField');
// AJAX functions
function expandUrl() {
const urlToExpand = url + '?shortUrl=' + $inputField.val() + '&key=' + apiKey;
fetch(urlToExpand)
.then(
response => {
if(response.ok) {
return response.json();
}
throw new Error('Request failed!');
},
networkError => {
console.log(networkError.message);
}
)
.then(
jsonResponse => {$responseField.append('<p> Your expanded URL is </p><p> ' + jsonResponse.longUrl + '</p>');
return jsonResponse;}
);
};
function shortenUrl() {
const urlWithKey = url + '?key=' + apiKey;
const urlToShorten = $inputField.val();
fetch(urlWithKey, {
method: 'POST',
headers: {
"Content-type": "application/json"
},
body: JSON.stringify({longUrl: urlToShorten})
})
.then(
response => {
if(response.ok) {
return response.json();
}
throw new Error('Request failed!');
},
networkError => console.log(networkError.message)
)
.then(
jsonResponse => {
console.log(jsonResponse);
$responseField.append('<p> Your shortened URL is </p><p>' + jsonResponse.id + '</p>');
return jsonResponse;
}
);
};
function expand() {
$responseField.empty();
expandUrl();
return false;
};
function shorten() {
$responseField.empty();
shortenUrl();
return false;
};
$expandButton.click(expand);
$shortenButton.click(shorten);