Skip to content

Commit 37241b6

Browse files
committed
fetch
1 parent 66fa857 commit 37241b6

File tree

26 files changed

+54760
-17
lines changed

26 files changed

+54760
-17
lines changed

5-regular-expressions/14-regexp-lookahead-lookbehind/article.md

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,19 +8,21 @@ That's what lookahead is for.
88

99
## Lookahead
1010

11-
The syntax is: `pattern:x(?=y)`, it means "match `pattern:x` only if followed by `pattern:y`".
11+
The syntax is: `pattern:x(?=y)`, it means "look for `pattern:x`, but match only if followed by `pattern:y`".
1212

13-
The euro sign is often written after the amount, so the regexp will be `pattern:\d+(?=€)` (assuming the price has no decimal point):
13+
For an integer amount followed by `subject:€`, the regexp will be `pattern:\d+(?=€)`:
1414

1515
```js run
1616
let str = "1 turkey costs 30€";
1717

1818
alert( str.match(/\d+(?=€)/) ); // 30 (correctly skipped the sole number 1)
1919
```
2020

21-
Or, if we wanted a quantity, then a negative lookahead can be applied.
21+
Let's say we want a quantity instead, that is a number, NOT followed by `subject:€`.
2222

23-
The syntax is: `pattern:x(?!y)`, it means "match `pattern:x` only if not followed by `pattern:y`".
23+
Here a negative lookahead can be applied.
24+
25+
The syntax is: `pattern:x(?!y)`, it means "search `pattern:x`, but only if not followed by `pattern:y`".
2426

2527
```js run
2628
let str = "2 turkeys cost 60€";
@@ -30,39 +32,43 @@ alert( str.match(/\d+(?!€)/) ); // 2 (correctly skipped the price)
3032

3133
## Lookbehind
3234

33-
Lookbehind allows to match a pattern only if there's something before.
35+
Lookahead allows to add a condition for "what goes after".
36+
37+
Lookbehind is similar, but it looks behind. That is, it allows to match a pattern only if there's something before.
3438

3539
The syntax is:
3640
- Positive lookbehind: `pattern:(?<=y)x`, matches `pattern:x`, but only if it follows after `pattern:y`.
3741
- Negative lookbehind: `pattern:(?<!y)x`, matches `pattern:x`, but only if there's no `pattern:y` before.
3842

39-
For example, let's change the price to US dollars. The dollar sign is usually before the number, so to look for `$30` we'll use `pattern:(?<=\$)\d+`:
43+
For example, let's change the price to US dollars. The dollar sign is usually before the number, so to look for `$30` we'll use `pattern:(?<=\$)\d+` -- an amount preceeded by `subject:$`:
4044

4145
```js run
4246
let str = "1 turkey costs $30";
4347

44-
alert( str.match(/(?<=\$)\d+/) ); // 30 (correctly skipped the sole number 1)
48+
alert( str.match(/(?<=\$)\d+/) ); // 30 (skipped the sole number)
4549
```
4650

47-
And for the quantity let's use a negative lookbehind `pattern:(?<!\$)\d+`:
51+
And, to find the quantity -- a number, not preceeded by `subject:$`, we can use a negative lookbehind `pattern:(?<!\$)\d+`:
4852

4953
```js run
5054
let str = "2 turkeys cost $60";
5155

52-
alert( str.match(/(?<!\$)\d+/) ); // 2 (correctly skipped the price)
56+
alert( str.match(/(?<!\$)\d+/) ); // 2 (skipped the price)
5357
```
5458

5559
## Capture groups
5660

5761
Generally, what's inside the lookaround (a common name for both lookahead and lookbehind) parentheses does not become a part of the match.
5862

59-
But if we want to capture something, that's doable. Just need to wrap that into additional parentheses.
63+
E.g. in the pattern `pattern:\d+(?!€)`, the `pattern:€` sign doesn't get captured as a part of the match.
64+
65+
But if we want to capture the whole lookaround expression or a part of it, that's possible. Just need to wrap that into additional parentheses.
6066

6167
For instance, here the currency `pattern:(€|kr)` is captured, along with the amount:
6268

6369
```js run
6470
let str = "1 turkey costs 30€";
65-
let reg = /\d+(?=(€|kr))/;
71+
let reg = /\d+(?=(€|kr))/; // extra parentheses around €|kr
6672

6773
alert( str.match(reg) ); // 30, €
6874
```

7-network/1-fetch/article.md renamed to 7-network/1-fetch-basics/article.md

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11

2-
# Fetch
2+
# Fetch basics
33

44
Method `fetch()` is the modern way of sending requests over HTTP.
55

@@ -104,7 +104,7 @@ img.style = 'position:fixed;top:10px;left:10px;width:100px';
104104
setTimeout(() => img.remove(), 2000);
105105
```
106106

107-
## The full syntax
107+
## Fetch API in detail
108108

109109
The second argument provides a lot of flexibility to `fetch` syntax.
110110

@@ -116,17 +116,21 @@ let promise = fetch(url, {
116116
headers: {
117117
"Content-Type": "text/plain;charset=UTF-8"
118118
},
119-
destination: "", // audio, audioworklet, document, embed, font...
119+
body: undefined // string, FormData, Blob, BufferSource, or URLSearchParams
120120
referrer: "about:client", // "" for no-referrer, or an url from the current origin
121121
referrerPolicy: "", // no-referrer, no-referrer-when-downgrade, same-origin...
122122
mode: "cors", // same-origin, no-cors, navigate, or websocket
123123
credentials: "same-origin", // omit, include
124124
cache: "default", // no-store, reload, no-cache, force-cache, or only-if-cached
125125
redirect: "follow", // manual, error
126-
integrity: "" // a hash, like "sha256-abcdef1234567890"
127-
keepalive: false // true
128-
body: "string" // FormData, Blob, BufferSource, or URLSearchParams
126+
integrity: "", // a hash, like "sha256-abcdef1234567890"
127+
keepalive: false, // true
128+
signal: undefined, // AbortController to abort request
129+
window: window // null
129130
})
131+
```
132+
133+
130134

131135

132136

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
`Origin` нужен, потому что `Referer` передаётся не всегда. В частности, при запросе с HTTPS на HTTP -- нет `Referer`.
2+
3+
Политика [Content Security Policy](http://en.wikipedia.org/wiki/Content_Security_Policy) может запрещать пересылку `Referer`.
4+
5+
По стандарту `Referer` является необязательным HTTP-заголовком, в некоторых браузерах есть настройки, которые запрещают его слать.
6+
7+
Именно поэтому, ввиду того, что на `Referer` полагаться нельзя, и придумали заголовок `Origin`, который гарантированно присылается при кросс-доменных запросах.
8+
9+
Что же касается "неправильного" `Referer` -- это из области фантастики. Когда-то, много лет назад, в браузерах были ошибки, которые позволяли подменить `Referer` из JavaScript, но они давно исправлены. Никакая "злая страница" не может его подменить.
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
importance: 5
2+
3+
---
4+
5+
# Зачем нужен Origin?
6+
7+
Как вы, наверняка, знаете, существует HTTP-заголовок `Referer`, в котором обычно указан адрес страницы, с которой инициирован запрос.
8+
9+
Например, при отправке `XMLHttpRequest` со страницы `http://javascript.ru/some/url` на `http://google.ru`, заголовки будут примерно такими:
10+
11+
```
12+
Accept:*/*
13+
Accept-Charset:windows-1251,utf-8;q=0.7,*;q=0.3
14+
Accept-Encoding:gzip,deflate,sdch
15+
Accept-Language:ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4
16+
Connection:keep-alive
17+
Host:google.ru
18+
*!*
19+
Origin:http://javascript.ru
20+
Referer:http://javascript.ru/some/url
21+
*/!*
22+
```
23+
24+
Как видно, здесь присутствуют и `Referer` и `Origin`.
25+
26+
Итак, вопросы:
27+
28+
1. Зачем нужен `Origin`, если `Referer` содержит даже более полную информацию?
29+
2. Может ли быть такое, что заголовка `Referer` нет или он неправильный?
30+

0 commit comments

Comments
 (0)