Cara menggunakan create response object javascript

Sorry if trivial, or already asked, I can't find any question about that. I dont't know if I'doing right too...

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:

self.addEventListener('fetch', function(event) {
if(event.request.url.indexOf("not_existing.json") > -1){
    var obj = { "Prop" : "Some value" };
    event.respondWith(
        new Response(obj, {
            ok: true,
            status: 222,
            url: '/'
        })
    );    
}});

Fetch Call:

fetch('not_existing.json')
.then(function(responseObj) {
    console.log('status: ', responseObj.status);
    return responseObj.json();
})
.then(function (data){
    console.log(data); 
});

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 var myResponse = new Response(body, init);

fetch() allows you to make network requests similar to XMLHttpRequest (XHR). The main difference is that the Fetch API uses Promises, which enables a simpler and cleaner API, avoiding callback hell and having to remember the complex API of XMLHttpRequest.

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 Request

Let's start by comparing a simple example implemented with an XMLHttpRequest and then with fetch. We just want to request a URL, get a response and parse it as JSON.

XMLHttpRequest

An XMLHttpRequest would need two listeners to be set to handle the success and error cases and a call to

fetch('./api/some.json')
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}

// Examine the text in the response
response.json().then(function(data) {
console.log(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
1 and
fetch('./api/some.json')
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}

// Examine the text in the response
response.json().then(function(data) {
console.log(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
2. Example from MDN docs.

function reqListener() {
var data = JSON.parse(this.responseText);
console.log(data);
}

function reqError(err) {
console.log('Fetch Error :-S', err);
}

var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.onerror = reqError;
oReq.open('get', './api/some.json', true);
oReq.send();

Fetch

Our fetch request looks a little like this:

fetch('./api/some.json')
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}

// Examine the text in the response
response.json().then(function(data) {
console.log(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});

We start by checking that the response status is 200 before parsing the response as JSON.

The response of a fetch() request is a Stream object, which means that when we call the

fetch('./api/some.json')
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}

// Examine the text in the response
response.json().then(function(data) {
console.log(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
4 method, a Promise is returned since the reading of the stream will happen asynchronously.

Response Metadata

In 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.

fetch('users.json').then(function(response) {
console.log(response.headers.get('Content-Type'));
console.log(response.headers.get('Date'));

console.log(response.status);
console.log(response.statusText);
console.log(response.type);
console.log(response.url);
});

Response Types

When we make a fetch request, the response will be given a

fetch('./api/some.json')
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}

// Examine the text in the response
response.json().then(function(data) {
console.log(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
5 of "", "" or "". These
fetch('./api/some.json')
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}

// Examine the text in the response
response.json().then(function(data) {
console.log(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
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

fetch('./api/some.json')
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}

// Examine the text in the response
response.json().then(function(data) {
console.log(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
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

fetch('./api/some.json')
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}

// Examine the text in the response
response.json().then(function(data) {
console.log(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
7.
fetch('./api/some.json')
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}

// Examine the text in the response
response.json().then(function(data) {
console.log(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
7 and
fetch('./api/some.json')
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}

// Examine the text in the response
response.json().then(function(data) {
console.log(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
6 responses are almost identical except that a
fetch('./api/some.json')
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}

// Examine the text in the response
response.json().then(function(data) {
console.log(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
7 response restricts the headers you can view to
fetch('users.json').then(function(response) {
console.log(response.headers.get('Content-Type'));
console.log(response.headers.get('Date'));

console.log(response.status);
console.log(response.statusText);
console.log(response.type);
console.log(response.url);
});
5,
fetch('users.json').then(function(response) {
console.log(response.headers.get('Content-Type'));
console.log(response.headers.get('Date'));

console.log(response.status);
console.log(response.statusText);
console.log(response.type);
console.log(response.url);
});
6,
fetch('users.json').then(function(response) {
console.log(response.headers.get('Content-Type'));
console.log(response.headers.get('Date'));

console.log(response.status);
console.log(response.statusText);
console.log(response.type);
console.log(response.url);
});
7,
fetch('users.json').then(function(response) {
console.log(response.headers.get('Content-Type'));
console.log(response.headers.get('Date'));

console.log(response.status);
console.log(response.statusText);
console.log(response.type);
console.log(response.url);
});
8,
fetch('users.json').then(function(response) {
console.log(response.headers.get('Content-Type'));
console.log(response.headers.get('Date'));

console.log(response.status);
console.log(response.statusText);
console.log(response.type);
console.log(response.url);
});
9, and
fetch('http://some-site.com/cors-enabled/some.json', {mode: 'cors'})
.then(function(response) {
return response.text();
})
.then(function(text) {
console.log('Request successful', text);
})
.catch(function(error) {
log('Request failed', error)
});
0.

An

fetch('./api/some.json')
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}

// Examine the text in the response
response.json().then(function(data) {
console.log(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
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:

  • fetch('http://some-site.com/cors-enabled/some.json', {mode: 'cors'})
    .then(function(response) {
    return response.text();
    })
    .then(function(text) {
    console.log('Request successful', text);
    })
    .catch(function(error) {
    log('Request failed', error)
    });
    2 only succeeds for requests for assets on the same origin, all other requests will reject.
  • fetch('./api/some.json')
    .then(
    function(response) {
    if (response.status !== 200) {
    console.log('Looks like there was a problem. Status Code: ' +
    response.status);
    return;
    }

    // Examine the text in the response
    response.json().then(function(data) {
    console.log(data);
    });
    }
    )
    .catch(function(err) {
    console.log('Fetch Error :-S', err);
    });
    7 will allow requests for assets on the same-origin and other origins which return the appropriate CORs headers.
  • fetch('http://some-site.com/cors-enabled/some.json', {mode: 'cors'})
    .then(function(response) {
    return response.text();
    })
    .then(function(text) {
    console.log('Request successful', text);
    })
    .catch(function(error) {
    log('Request failed', error)
    });
    4 will always perform a before making the actual request.
  • fetch('http://some-site.com/cors-enabled/some.json', {mode: 'cors'})
    .then(function(response) {
    return response.text();
    })
    .then(function(text) {
    console.log('Request successful', text);
    })
    .catch(function(error) {
    log('Request failed', error)
    });
    5 is intended to make requests to other origins that do not have CORS headers and result in an
    fetch('./api/some.json')
    .then(
    function(response) {
    if (response.status !== 200) {
    console.log('Looks like there was a problem. Status Code: ' +
    response.status);
    return;
    }

    // Examine the text in the response
    response.json().then(function(data) {
    console.log(data);
    });
    }
    )
    .catch(function(err) {
    console.log('Fetch Error :-S', err);
    });
    8 response, but as stated, this isn't possible in the window global scope at the moment.

To define the mode, add an options object as the second parameter in the fetch request and define the mode in that object:

fetch('http://some-site.com/cors-enabled/some.json', {mode: 'cors'})
.then(function(response) {
return response.text();
})
.then(function(text) {
console.log('Request successful', text);
})
.catch(function(error) {
log('Request failed', error)
});

Chaining Promises

One 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.

function status(response) {
if (response.status >= 200 && response.status < 300) {
return Promise.resolve(response)
} else {
return Promise.reject(new Error(response.statusText))
}
}

function json(response) {
return response.json()
}

fetch('users.json')
.then(status)
.then(json)
.then(function(data) {
console.log('Request succeeded with JSON response', data);
}).catch(function(error) {
console.log('Request failed', error);
});

We define the

fetch('http://some-site.com/cors-enabled/some.json', {mode: 'cors'})
.then(function(response) {
return response.text();
})
.then(function(text) {
console.log('Request successful', text);
})
.catch(function(error) {
log('Request failed', error)
});
8 function which checks the response.status and returns the result of
fetch('http://some-site.com/cors-enabled/some.json', {mode: 'cors'})
.then(function(response) {
return response.text();
})
.then(function(text) {
console.log('Request successful', text);
})
.catch(function(error) {
log('Request failed', error)
});
9 or
function status(response) {
if (response.status >= 200 && response.status < 300) {
return Promise.resolve(response)
} else {
return Promise.reject(new Error(response.statusText))
}
}

function json(response) {
return response.json()
}

fetch('users.json')
.then(status)
.then(json)
.then(function(data) {
console.log('Request succeeded with JSON response', data);
}).catch(function(error) {
console.log('Request failed', error);
});
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
fetch('./api/some.json')
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}

// Examine the text in the response
response.json().then(function(data) {
console.log(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
4 method which again returns a Promise from the
function status(response) {
if (response.status >= 200 && response.status < 300) {
return Promise.resolve(response)
} else {
return Promise.reject(new Error(response.statusText))
}
}

function json(response) {
return response.json()
}

fetch('users.json')
.then(status)
.then(json)
.then(function(data) {
console.log('Request succeeded with JSON response', data);
}).catch(function(error) {
console.log('Request failed', error);
});
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 Request

It'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

function status(response) {
if (response.status >= 200 && response.status < 300) {
return Promise.resolve(response)
} else {
return Promise.reject(new Error(response.statusText))
}
}

function json(response) {
return response.json()
}

fetch('users.json')
.then(status)
.then(json)
.then(function(data) {
console.log('Request succeeded with JSON response', data);
}).catch(function(error) {
console.log('Request failed', error);
});
4 and
function status(response) {
if (response.status >= 200 && response.status < 300) {
return Promise.resolve(response)
} else {
return Promise.reject(new Error(response.statusText))
}
}

function json(response) {
return response.json()
}

fetch('users.json')
.then(status)
.then(json)
.then(function(data) {
console.log('Request succeeded with JSON response', data);
}).catch(function(error) {
console.log('Request failed', error);
});
5 parameters in the fetch() options.

fetch(url, {
method: 'post',
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
},
body: 'foo=bar&lorem=ipsum'
})
.then(json)
.then(function (data) {
console.log('Request succeeded with JSON response', data);
})
.catch(function (error) {
console.log('Request failed', error);
});

Sending Credentials with a Fetch Request

Should you want to make a fetch request with credentials such as cookies, you should set the

function status(response) {
if (response.status >= 200 && response.status < 300) {
return Promise.resolve(response)
} else {
return Promise.reject(new Error(response.statusText))
}
}

function json(response) {
return response.json()
}

fetch('users.json')
.then(status)
.then(json)
.then(function(data) {
console.log('Request succeeded with JSON response', data);
}).catch(function(error) {
console.log('Request failed', error);
});
7 of the request to
function status(response) {
if (response.status >= 200 && response.status < 300) {
return Promise.resolve(response)
} else {
return Promise.reject(new Error(response.statusText))
}
}

function json(response) {
return response.json()
}

fetch('users.json')
.then(status)
.then(json)
.then(function(data) {
console.log('Request succeeded with JSON response', data);
}).catch(function(error) {
console.log('Request failed', error);
});
8.

fetch(url, {
credentials: 'include'
})

FAQ

How 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.