fetch: talking to servers
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
fetch(url) is how a page asks a server for data: it sends an HTTP request and hands back a promise straight away. Follow an eight-line script that loads one user, from the request and the paused await, through the response, the res.ok check and res.json(), to the printed name, and see why a 404 reply does not make fetch fail on its own.
5 أسئلة سريعة
اختر إجابة لتعرف السبب. تُحفَظ نتيجتك مع تقدّمك.
01What does fetch("/api/users/7") give back the moment it is called?
fetch starts the request and returns a promise at once. The promise fulfils with a Response later, when the status and headers arrive.
02In the eight-line script, which does the console print first?
await pauses only loadUser. Control goes back to the caller, line 8 prints waiting..., and Ada is printed later when the data has arrived.
03The server answers 404 Not Found. What happens to fetch's promise?
A reply came back, so fetch fulfils. res.status is 404 and res.ok is false; your code must check ok, as line 3 does.
04For which status is res.ok true?
Response.ok is true for the success range, 200 to 299, and false for everything else, such as 404 or 500.
05Why is there a second await in const user = await res.json()?
fetch fulfils as soon as the headers arrive. Reading and parsing the body takes more time, so res.json() returns its own promise.
المسرد
- fetch()
- The built-in function that sends an HTTP request and returns a promise for the Response. Defined by the WHATWG Fetch Standard.
- HTTP request
- A message a browser sends to a server, such as GET /api/users/7, asking for a resource.
- HTTP response
- The server's reply: a status line (such as 200 OK), headers, and a body.
- Status code
- The number in a response that says how it went: 200 success, 404 not found, 500 server error.
- Response
- The object fetch's promise fulfils with. It has status, ok, headers and methods such as json() and text() to read the body.
- Promise
- An object for a result that arrives later. It is pending, then fulfilled with a value or rejected with an error.
- await
- Inside an async function, pauses that function until a promise settles, then gives back its value (or throws its error).
- JSON
- JavaScript Object Notation: a text format for data, such as {"id":7,"name":"Ada"}. res.json() parses it into an object.
الملاحظات والمصادر
- fetch is not part of the JavaScript language itself: it is a web API defined by the WHATWG Fetch Standard and built into every modern browser. Node.js has it built in since version 18. Promises, async and await are part of the language (ECMA-262).
- A relative address such as "/api/users/7" is resolved against the page's own address, so the request goes to the server that sent the page. Asking a different site needs that site's permission (CORS). In Node.js, give fetch a full address such as https://example.com/api/users/7.
- fetch's promise fulfils as soon as the status and headers arrive; the body may still be downloading. That is why reading it with res.json() or res.text() returns another promise. A body can be read only once.
- fetch rejects (usually with a TypeError) only when no response comes back: no connection, a blocked cross-site request or a bad address. If you cancel a request with an AbortController, it rejects with an AbortError instead. To handle every failure, wrap the awaits in try { ... } catch (err) { ... }, or call loadUser().catch(...).
- fetch makes a GET request by default. To send data, pass options: fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) }).
- The memory boxes show res.status and user.name to save space; res really holds the whole Response object and user the whole parsed object. The figure shows HTTP/1.1 text; newer HTTP versions carry the same status, headers and body in a binary form. The console panel shows the error as Error: 404; Chrome's console labels an uncaught rejection in full, as Uncaught (in promise) Error: 404.
- MDN: Window.fetch()
- MDN: Using the Fetch API
- MDN: Response.ok
- MDN: Response.json()
- MDN: async function
- MDN: await
- MDN: Promise
- MDN: HTTP response status codes
- MDN: Cross-Origin Resource Sharing (CORS)
- WHATWG Fetch Standard
- ECMAScript Language Specification: Promise objects
- ECMAScript Language Specification: async functions
- Node.js: global fetch
اختبار يتاح بعد الخطوة الأخيرة.