Sorry if trivial, or already asked, I can't find any question about that. I dont't know if I'doing right too... Show
I just beginned learning service workers: I'd like to return some json object from a service worker for a specific request. N.B.: The code is just testing/learning code: Service Worker Fetching Event:
Fetch Call:
I know that the service worker catches the request, because on "console.log('status: ', responseObj.status);" I get "222", but the script breaks on "return responseObj.json();" with error "Uncaught (in promise) SyntaxError: Unexpected token o in JSON at position 1" If I return "plain text" from service worker, and read it with "responseObj.text()" all works great! On this link "https://developer.mozilla.org/en-US/docs/Web/API/Response/Response" it seems I have only to write the body on Response constructor
Browser support: chrome 42, Supported 42 firefox 39, Supported 39 edge 14, Supported 14 safari 10.1, Supported 10.1 The Fetch API has been available in the Service Worker global scope since Chrome 40, but it'll be enabled in the window scope in Chrome 42. There is also a rather fetching polyfill by GitHub that you can use today. If you've never used Promises before, check out Introduction to JavaScript Promises. Basic Fetch RequestLet's start by comparing a simple example implemented with an XMLHttpRequestAn 1 and 2. Example from MDN docs.
FetchOur fetch request looks a little like this:
We start by checking that the response status is 200 before parsing the response as JSON. The response of a 4 method, a Promise is returned since the reading of the stream will happen asynchronously.Response MetadataIn the previous example we looked at the status of the object as well as how to parse the response as JSON. Other metadata we may want to access, like headers, are illustrated below.
Response TypesWhen we make a fetch request, the response will be given a 5 of "", "" or "". These 9 indicate where the resource has come from and can be used to inform how you should treat the response object.When a request is made for a resource on the same origin, the response will have a 6 type and there aren't any restrictions on what you can view from the response.If a request is made for a resource on another origin which returns the CORs headers, then the type is 7. 7 and 6 responses are almost identical except that a 7 response restricts the headers you can view to 5, 6, 7, 8, 9, and 0.An 8 response is for a request made for a resource on a different origin that doesn't return CORS headers. With an opaque response we won't be able to read the data returned or view the status of the request, meaning we can't check if the request was successful or not.You can define a mode for a fetch request such that only certain requests will resolve. The modes you can set are as follows:
To define the mode, add an options object as the second parameter in the
Chaining PromisesOne of the great features of promises is the ability to chain them together. For fetch, this allows you to share logic across fetch requests. If you are working with a JSON API, you'll need to check the status and parse the JSON for each response. You can simplify your code by defining the status and JSON parsing in separate functions which return promises, freeing you to only worry about handling the final data and the error case.
We define the 8 function which checks the response.status and returns the result of 9 or 0, which return a resolved or rejected Promise. This is the first method called in our fetch() chain, if it resolves, we then call our 4 method which again returns a Promise from the 3 call. After this we have an object of the parsed JSON. If the parsing fails the Promise is rejected and the catch statement executes.The great thing with this is that you can share the logic across all of your fetch requests, making code easier to maintain, read and test. POST RequestIt's not uncommon for web apps to want to call an API with a POST method and supply some parameters in the body of the request. To do this we can set the 4 and 5 parameters in the fetch() options.
Sending Credentials with a Fetch RequestShould you want to make a fetch request with credentials such as cookies, you should set the 7 of the request to 8.
FAQHow do I cancel a fetch() request?At the moment there is no way to cancel a fetch, but this is being discussed on GitHub. H/T @jaffathecake for this link. Apa 2 struktur pembentuk JSON?JSON terbuat dari dua struktur: Kumpulan pasangan nama/nilai. Pada beberapa bahasa, hal ini dinyatakan sebagai objek (object), rekaman (record), struktur (struct), kamus (dictionary), tabel hash (hash table), daftar berkunci (keyed list), atau associative array.
JSON parse untuk apa?JSON.parse() dapat mengambil fungsi sebagai argumen kedua yang dapat mengubah nilai objek sebelum mengembalikannya.
Tipe data apa saja yang ada pada JSON?Key harus berupa string, dan value boleh berupa salah satu dari enam tipe data JSON yang ada: string, angka, objek, array, boolean, atau null.
Mengapa kini JSON paling sering digunakan sebagai notasi script pada API daripada XML menurut kalian?Berbeda dengan XML (extensive markup language) dan format lainnya yang memiliki fungsi serupa, JSON memiliki struktur data yang sederhana dan mudah dipahami. Itulah mengapa JSON sering digunakan pada API.
|