Add a simple user Using Fetch:
function addUserWithFetch(_lastName, _firstName ) {
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
"LastName": _lastName,
"FirstName": _firstName
});
requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
const uri = "http://localhost:5000/api/employees/AddTempEmployee";
const request = new Request(uri, requestOptions);
fetch(request, requestOptions)
.then(response => response.json())
.then(result => console.log(result))
.catch(error => console.log('error', error));
}
Functions to get Data with Authorization token:
function _getDataWithToken(_request) {
return fetch(_request)
.then(response => {
if (response.status === 200) {
return response.json();
}
throw new Error('Resource not found');
})
.then(data => {
return data;
})
.catch(err => {
//promise rejected, handle the error
console.log('Rejected: ', err);
});
}
// Caller Function
async function GetDataWithToken() {
let token = await _ReadTokenFromDisk();
var uri = baseUri + "weatherforecast/limit/2"
var myHeaders = new Headers();
myHeaders.append("Authorization", "bearer " + token);
var requestOptions = {
method: 'GET',
headers: myHeaders,
};
const request = new Request(uri, requestOptions);
let data = await _getDataWithToken(request);
console.log(data);
}
Caller and Calee Fetch API:
function _getData(_request) {
return fetch(_request)
.then(response => {
if (response.status === 200) {
return response.json();
}
throw new Error('Resource not found');
})
.then(data => {
return data;
})
.catch(err => {
//promise rejected, handle the error
console.log('Rejected: ', err);
});
}
async function GetData() {
const uri = "http://mobile.ids-systems.net/data/states.json"
let request = new Request(uri);
const options = {
method: 'GET',
cache: "no-store",
};
request.options = options;
let data = await _getData(request);
console.log(data);
}
Read Token file from disk:
async function _ReadTokenFromDisk() {
// Reads an on disk file.
let uri = "./AdminToken.txt";
try {
let response = await fetch(uri, getOptions());
return await response.text();
} catch (error) {
console.log(error);
}
}
async function ReadTokenFromDisk() {
let token = await _ReadTokenFromDisk();
console.log(token);
//TestWithToken(token);
//getWeatherWithToken(token);
}
Another example of caller and callee:
function Callee() {
const options = {
method: 'GET',
cache: "no-store",
};
const uri = baseUri + "WeatherForecast";
const request = new Request(uri, options);
request.type = "GET";
return fetch(request)
.then(response => {
//promise resolved, do something with result
//console.log('Resolved: ', response);
if (response.status === 200) {
return response.json();
}
throw new Error('Resource not found');
})
.then(data => {
return data;
})
.catch(err => {
//promise rejected, handle the error
console.log('Rejected: ', err);
});
}
async function Caller() {
var j = await Callee();
console.log(j);
}