Example 1: js fetch 'post' json
//Obj of data to send in future like a dummyDb
const data = { username: 'example' };
//POST request with body equal on data in JSON format
fetch('https://example.com/profile', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then((response) => response.json())
//Then with the data from the response in JSON...
.then((data) => {
console.log('Success:', data);
})
//Then with the error genereted...
.catch((error) => {
console.error('Error:', error);
});
// Yeah
Example 2: Add no cores to fetch
// There were no quick access to mode and credentials to other fetch answers.
// Data you'll be sending
const data = { funny: "Absolutely not", educational: "yas" }
fetch('https://example.com/api/', {
method: 'POST', // The method
mode: 'no-cors', // It can be no-cors, cors, same-origin
credentials: 'same-origin', // It can be include, same-origin, omit
headers: {
'Content-Type': 'application/json', // Your headers
},
body: JSON.stringify(data),
}).then(returnedData => {
// Do whatever with returnedData
}).catch(err => {
// In case it errors.
})
Example 3: request api
REQUEST :(request url,http methods,header,query param, param,body,cookie)
1-)Request Url where we have Endpoint (domain:Port/Endpoints)
2-)HTTP METHODS(Get, Post, Put, Patch, Delete, Header)
Get: For to retrieve resources from the server
Post: to send or add resource to the server
Put: For update the resources in the server
Patch: For partial update the resource
Delete: For deleting the resource in the server
Head: To get header from the response not the body
3-)HEADER is metadata is about the request,
basically providing more information along
with the request.
-Content Type header : to specify what kind of
data we are sending to the server
-Accept Header : to specify what kind of data
format you want to get in the response like (json or xml)
-Authorization header : used to provide the
Bearer token in many api's.
4-)Query Parameter: A key value pair usually
for filtering result
5-)Parameter: for identifying single resource
among the list of resources.
6-)Payload(BODY): for POST,PUT,PATCH request
(json,xml,plainText,URL encoded for data)
7-)Cookie