sending request via Fetch API from ASP.NET razor view - asp.net

I'm trying to send a request via Feth
ch API to the remote api that serves over Http. I'm getting this error on my developer tools window.
Here is js.
(function () {
login();
})();
function login() {
document.getElementById("submitBtn").addEventListener("click", function () {
sendLoginAjax();
});
};
function sendLoginAjax(userName, password) {
var form = document.getElementById("loginForm");
var params = "UserName=" + userName + "&Password" + password + "&IPs=";
// Bind the FormData object and the form element
const FD = new FormData();
FD.append("func", "Login");
FD.append("params", params);
fetch("http://isapi.mekashron.com/soapclient/soapclient.php?URL=http://isapi.icu-tech.com/icutech-test.dll%2Fwsdl%2FIICUTech", {
method: 'POST',
body: FD
}).then(result => result.json()).then(
(result) => {
console.log(result);
}
);
}
I don't know what I should do to solve it.
Have any fix?

Related

K6 trigger ASP.NET Core server function

I have an ASP.NET Core Web API project that is using SignalR, I have a hub there which I am connecting to it using k6 (I want to do some load testings) I manage to connect to my hub but I can not figure out how to call a function from my server, my code is
import ws from 'k6/ws';
import { check } from 'k6';
export default function () {
var token = "Bearer userAccessToken";
const url = 'wss://localhost:5001/session';
const params = { headers: { "Authorization": token } };
const res = ws.connect(url, params, function (socket) {
socket.on('open', () => {
console.log("opened");
socket.send(JSON.stringify({ UserId: "aUserId", GameId: "AGameId" }))
});
socket.on('close', () => console.log('disconnected'));
});
check(res, { 'status is 101': (r) => r && r.status === 101 });
}
My function is called joinGameSession and it takes two variables the user id and the gameId
public async Task<bool> JoinGameSession(JoinGameRequest request)
{
return true;
}
I have managed to trigger functions using Microsoft's SignalR client.
const signalR = require("#microsoft/signalr");
require('dotenv').config();
var token = process.env.token ?? "";
var questionIndex = 0;
let connection = new signalR.HubConnectionBuilder()
.withUrl("http://localhost:5000/session", { headers: { "Authorization": token } })
.withAutomaticReconnect()
.build();
connection.start().then(() => {
connection.invoke("JoinGameSession", { UserId: "a", GameId: "x" });
}).catch(e => {
console.log(e);
})
but I can not do it with k6, is there any other tools to achieve my goal?
Thank you.

API is sending no data when calling from another project & showing HTTP error 204

I have a method in an ASP.net API, which sends JWT token when it gets a Request with HTTP Get Method. On fiddler when I call this API, everything works fine; but when I call same API with another project (made in angular 8) I get HTTP 204 Error and no data.
In Angular Project I call this API on NgOnInit of my Component.
Here is code of API
[HttpGet("[action]")]
public string GetToken()
{
try
{
string key = "FIPL#321456222222222222222222222222222222222222222222222222222222222222222222"; //Secret key which will be used later during validation
var issuer = "http://localhost:1424/"; //normally this will be your site URL
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
//Create a List of Claims, Keep claims name short
var permClaims = new List<Claim>();
permClaims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()));
//permClaims.Add(new Claim("valid", "1"));
//permClaims.Add(new Claim("userid", "1"));
//permClaims.Add(new Claim("name", "bilal"));
//Create Security Token object by giving required parameters
var token = new JwtSecurityToken(issuer, //Issure
issuer, //Audience
permClaims,
expires: DateTime.Now.AddDays(1),
signingCredentials: credentials);
var jwt_token = new JwtSecurityTokenHandler().WriteToken(token);
enter image description here
return (String)jwt_token;
}
catch (Exception ex)
{
return (string)ex.Message ;
}
}
Here is code of angular where API is called.
ngOnInit() {
let obj = JSON.parse(localStorage.getItem("Auth"));
this.DepartmentModel._iBPNo = obj.BPNo;
this.DepartmentModel._iLoginNo = obj.LoginNo;
//Here I am Calling the API to get token
this.httpServices.get("http://localhost:52484/api/Token/gettoken/", null, (data) => {
alert(JSON.stringify(data));
localStorage.setItem("Token", JSON.stringify(data));
}, (error) => {
console.log(error);
});
if (JSON.parse(sessionStorage.getItem("PDEP"))) {
this.DeptNo = JSON.parse(sessionStorage.getItem("PDEP"));
this.LoadData();
}
}
Here is link to my fiddler Page Response.
You can try subscribing to an HTTP request directly :
this.httpServices.get("http://localhost:52484/api/Token/gettoken").subscribe((data) => {
alert(JSON.stringify(data));
localStorage.setItem("Token", JSON.stringify(data));
}, (error) => {
console.log(error);
});

Properly fetching cached responses from workbox service worker

I was experimenting with workbox and service workers in general. I tried using NetworkFirst Strategy for my api calls. Console seems its working as expected but I could not display the cached response from service worker. Same is happening when using CacheFirst, response is not recieved by my dom render scripts. Am I missing something?
importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.0.0/workbox-sw.js');`
if (workbox) {
console.log(`Yay! Workbox is loaded 🎉`);
workbox.precaching.precacheAndRoute([]);
const cacheName = 'collection';
workbox.routing.registerRoute(
new RegExp('http://13.232.112.165/api/'),
workbox.strategies.networkFirst()
);
/*
const bgSyncPlugin = new workbox.backgroundSync.Plugin('post-req-queue', {
maxRetentionTime: 24 * 60 // Retry for max of 24 Hours
});
workbox.routing.registerRoute(
new RegExp("http://13.232.112.165/api/"),
workbox.strategies.networkOnly({
plugins: [bgSyncPlugin]
}),
'POST'
);
workbox.routing.registerRoute(
new RegExp("http://13.232.112.165/api/"),
workbox.strategies.networkOnly({
plugins: [bgSyncPlugin]
}),
'PUT'
);
workbox.routing.registerRoute(
new RegExp("http://13.232.112.165/api/"),
workbox.strategies.networkOnly({
plugins: [bgSyncPlugin]
}),
'DELETE'
);
*/
} else {
console.log(`Boo! Workbox didn't load 😬`);
}`
My Api call is as follows :
async function getAccounts() {
url = backend_uri+"accounts";
try{
var jsonResponse = await fetch(url, {headers: {
'Authorization' : "Token "+localStorage.getItem('user-token')
}});
const json = await jsonResponse.json();
const accounts = await json;
let renderString = "";
await accounts.forEach(element => {
renderString = renderString + `<div class='card'><div class='card-body'><strong>${element.name}</strong></div></div>`
});
containerElement.innerHTML += renderString;
}catch(e) {
console.log(e);
}
}
Should api calls in PWA made differently?
(I don't think your question is related to Workbox or PWAs; it appears to be more about using the Fetch API.)
There are some extra awaits and a few other issues that I see with your code; can you try the following?
async function getAccounts() {
const url = `${backend_uri}accounts`;
const response = await fetch(url, {
headers: {
'Authorization' : "Token "+localStorage.getItem('user-token')
},
});
const accounts = await response.json();
const divs = accounts.map(account => `<div class='card'>
<div class='card-body'>
<strong>${account.name}</strong>
</div>
</div>`);
containerElement.innerHTML += divs.join('');
}

Firebase Callable function with JWT Authentication and Google Sheets V4 API

I want to implement firebase callable function with JWT Authentication and fetching data from Google Sheet, using Google Sheets V4 API.
For test I tried to use Example Spreadsheet but Sheets API not activated for that Spreadsheet and I cloned it on my own drive and use it for testing.
References:
My code based on solution described in this question How to use Google sheets API while inside a google cloud function and Accessing Google APIs using Service account in Node.JS
Also I have got two important information: "Service Account".json and API Key. I save API Key in api_key.json but didn't find examples how to use it with Google Sheets V4 API:
{
key: "xxxxxx"
}
test() callable function which doesn't require any authentication works fine:
exports.test = functions.https.onCall((data, context) => {
return { text: data.text };
});
Calling test() function somewhere on client (in Browser):
function getTest() {
console.log("clicked getTest()");
var test = firebase.functions().httpsCallable('test');
test({text: '12345'}).then(function(result) {
console.log(result);
}).catch(function(error) {
console.log(error.code);
console.log(error.message);
});
}
Calling getData() somewhere on client (in Browser):
function requestData() {
console.log("clicked requestData()");
//https://firebase.google.com/docs/functions/callable
//getData() function described in functions/index.js
var getData = firebase.functions().httpsCallable('getData');
getData(null).then(function (result) {
// Read result of the Cloud Function.
console.log(result); //<------- Expected rows from Spreadsheet????
}).catch(function(error) {
console.log(error.code);
console.log(error.message);
});
}
**Thank you, F10. I corrected code.
index.js:
'use strict'
const functions = require('firebase-functions');
const { google } = require('googleapis');
var serviceAccount = require("./credentials/owner-service-account-gcloud.json");
function getJwt() {
// Define the required scopes.
var scopes = [
'https://www.googleapis.com/auth/spreadsheets'
];
return new google.auth.JWT(
serviceAccount.client_email,
null,
serviceAccount.private_key,
scopes
);
}
function getSpreadsheetDate(jwt) {
return new Promise((resolve, reject) => {
jwt.authorize((error, access_token) => {
if (error) {
console.log('Error in jwt.authorize: ' + error);
reject(error);
} else {
// access_token ready to use to fetch data and return to client
const sheets = google.sheets({ version: 'v4', access_token });
// set auth as a global default:
google.options({ auth: jwt }); //<----------------------
const request = {
auth: jwt,
spreadsheetId: 'xxxx',
range: 'Class Data!A2:E', //'Class Data!A2:E',
}
sheets.spreadsheets.values.get(request, (err, response) => {
console.log("inside: sheets.spreadsheets.values.get() -------------------------------");
if (err) {
console.log('The Sheets API returned an error: ' + err);
//The API returned an error: Error: API key not valid. Please pass a valid API key.
reject(err);
};
try {
var numRows = response.data.values ? response.data.values.length : 0;
console.log('%d rows retrieved.', numRows);
console.log("response.data:-------------------------------");
console.log(response.data.values);
resolve(response.data.values);
} catch (err) {
console.log("Error processing Sheets API response: " + err);
reject(err);
}
})
}
})
})
}
exports.getData = functions.https.onCall((data, context) => {
console.log("getData()---------------------------");
if (!context.auth) {
throw new functions.https.HttpsError('failed-precondition', 'The function must be called ' + 'while authenticated.');
} else {
console.log("context.auth ------------ OK");
const uid = context.auth.uid;
console.log(uid);
var jwt = getJwt();
console.log("getJwt() --------------- OK");
return getSpreadsheetDate(jwt); //<------------ Requested Spreadsheet's Data
}
})
exports.test = functions.https.onCall((data, context) => {
return { text: data.text };
});
There's a solution that uses googleapis instead of the auth library to do the authentication with JWT. Regarding your token inquiries, you could check the OAuth 2.0 for client-side web applications documentations, which explains the steps to do the authentication.

fetch api not working after Network change - react native android

I have one application in which user can login and see some info.
Issue:
user able to login and see info and logout any number of times before changing network.but once user change network(from wifi to mobile or vice versa) and try to login and fetch information. it's throwing error:Network request failed at XMLHttpRequest.xhr.onerror (fetch.js:441)
Note: i am using fetch api for network call.
Fetch Api call:
export const request = async function request(path, body = null, method = 'GET') {
try {
const headers = {
'Content-Type': body instanceof FormData ? 'multipart/form-data' : 'application/json',
};
const token = await AsyncStorage.getItem('authToken');
if (token) {
headers.Authorization = token;
}
const config = {
method,
url: Config.API_URL + path,
headers,
};
if (!['HEAD', 'GET'].includes(method.toUpperCase())) {
config.body = body instanceof FormData ? body : JSON.stringify(body);
}
const response = await fetch(Config.API_URL + path, config);
const data = await response.json();
if (response.status >= 400) {
throw data.error;
}
return data;
} catch (e) {
console.log('Error', path, e);
return Promise.reject(e);
}
Error
Network request failed
at XMLHttpRequest.xhr.onerror (fetch.js:441)
at XMLHttpRequest.dispatchEvent (event-target.js:172)
at XMLHttpRequest.setReadyState (XMLHttpRequest.js:567)
at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:397)
at XMLHttpRequest.js:503
at RCTDeviceEventEmitter.emit (EventEmitter.js:179)
at MessageQueue.__callFunction (MessageQueue.js:351)
at MessageQueue.js:116
at MessageQueue.__guardSafe (MessageQueue.js:314)
SDK Version:
compileSdkVersion: 25
buildToolsVersion: "25.0.2"
minSdkVersion: 16
targetSdkVersion: 25
I am beginner in react native. not able to identify the problem. any help will be appreciate.
Thanks

Resources