Handle asmx C# Exception with fetch API - javascript

First of all sorry for my English...
I have an asmx in C# that send data in json with an fetch API Call in the client side, i was using the jQuery.Ajax call before, but i want to start using fetch API.
This is how i do the Fetch Call.
I call the function fetchcall passing the url and if is needed the JS object with the parameters to be send by POST
const jdata = await fetchcall(url, "")
Then in my function i do this
async function fetchcall(url, data) {
const PostData = {
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
dataType: 'json'
//credentials: 'include'
}
if (data) { PostData.body = JSON.stringify(data) }
try {
const response = await fetch(url, PostData)
const json = await (handleErrors(response)).json();
//This is a temporary solution to the problem
if (json == 'Su sesion ha expirado favor de ir a pagina de login e iniciar session') {
alert(json);
return false;
}
return json
} catch (e) {
console.log(e)
}}
And this is the handleErrors function
function handleErrors(response) {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
}
Right now i am testing the error without sending the credentials, so i get a error for the Session
And in my C# asmx i have this
[WebMethod(Description = "Load Countries", EnableSession = true)]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
public string fillcbocountries()
{
var authCookie = Session["uid"];
if (authCookie == null)
throw new Exception("Your session has expired please go to login page and start session");}
With that the web services is throwing me an error with the message of Your session has expired please go to login page and start session
But wen i check the response of the fetch API in the handleError function i only get a statusText:"Internal Server Error" and i want the message that the server respond.
With jQuery.Ajax i do this
error: function (xhr, textStatus, error) {
var errorM = $.parseJSON(xhr.responseText);
console.log(errorM.Message)
}
And i get the
Your session has expired please go to login page and start session
Thank you for the help and regards

I discovered how to handle the error correctly if an exception is sent from C#
I removed the handleErrors function and check the response inside the fetchcall
so if the response.ok is false then i check the json data that the server respond and get the json.Message.
This is the end code
async function fetchcall(url, data) {
const PostData = {
method: 'POST',
headers: {
"Accept": "application/json",
'Content-Type': 'application/json; charset=utf-8'
},
dataType: 'json',
credentials: 'include'
}
if (data) { PostData.body = JSON.stringify(data) }
try {
//const url = 'services/common.asmx/fillcbopais'
const response = await fetch(url, PostData)
const jdata = await response.json();
if (!response.ok) {
alert(jdata.Message);
throw Error(jdata.Message)
}
return json
} catch (e) {
console.log(e)
}}
In case someone else has this problem I hope I can help

Related

How to handle 429 errors with fetch

I am trying to retrieve data from my own rest api. On the backend side I have express-rate-limit in use. Now I am trying to handle 429 error when it occurs. I want to display something to the user like "
Too many requests, please try again later.
How can I read the statusText of the error?
try {
const data = await fetch("http://localhost:5000/login", {
method: "POST",
body: JSON.stringify(
{
email
password
}
),
headers: {
"Accept": "application/json",
'Content-Type': 'application/json'
}
})
const result = await data.json()
if (data.status !== 200) {
throw new Error(result.detail.message)
}
console.log(result)
} catch (e) {
console.log(e) //shows: There was an error SyntaxError
}

Bad respond when trying to get authentication token for Reddit api 'Application Only OAuth'

So i been trying to get access to the reddit api.
I registered to reddit. verified my mail. opened an app and got my credentials.
Followed this official documentation and also came across to this tutorial
All my efforts have failed and don't get any respond.
I am using nodejs. but also tried in postman and failed.
Tried 2 options using fetch and using axios:
const axios = require('axios');
const fetch = require('node-fetch')
const { URLSearchParams } = require('url')
class RedditApi {
clientId2 = "get ur own credentials by opening an app here https://www.reddit.com/prefs/apps";
clientSecret2 = "get ur own credentials by opening an app here https://www.reddit.com/prefs/apps";
authenticationUrl = `https://www.reddit.com/api/v1/access_token`;
BASE_URL = 'https://www.reddit.com/';
tokenAuth = null;
tokenExpirationTime = null;
currencyObj = null;
constructor(currencyObj) {
this.currencyObj = currencyObj;
console.log("constructor service")
}
async getAuthToken() {
const bodyParams = new URLSearchParams({
grant_type: "https://oauth.reddit.com/grants/installed_client",
device_id: "DO_NOT_TRACK_THIS_DEVICE"
});
console.log(this.clientId2, 'this.clientId');
debugger;
const headersObj = {
'Authorization': `Basic ${Buffer.from(`${this.clientId2}:`).toString('base64')}`,
'Content-Type': 'application/x-www-form-urlencoded',
};
let response = null;
try {
response = await axios.post(this.authenticationUrl,
bodyParams,
{
headers: headersObj
});
debugger;
} catch (error) {
debugger;
console.error(error);
console.log(error.stack);
return null;
}
}
async getAuthToken2() {
try {
// Creating Body for the POST request which are URL encoded
const params = new URLSearchParams()
params.append('grant_type', 'https://www.reddit.com/api/v1/access_token')
params.append('device_id', 'DO_NOT_TRACK_THIS_DEVICE')
// Trigger POST to get the access token
const tokenData = await fetch('https://oauth.reddit.com/grants/installed_client', {
method: 'POST',
body: params,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `Basic ${Buffer.from(`${this.clientId2}:`).toString('base64')}` // Put password as empty
}
}).then(res => {
debugger;
return res.text()
})
debugger;
if (!tokenData.error) {
debugger;
res.send(trendingResult)
}
res.status(tokenData.error).send(tokenData.message)
} catch (error) {
debugger;
console.log(error)
}
}
}
module.exports = RedditApi;
when using axios i get this respond: "Request failed with status code 401"
When using fetch i get this respond: "'403 Forbidden\nRequest forbidden by administrative rules.\n\n'"
Anybody knows what is the problem and how can i fix it?
Many thanks!

Response.redirect() is not a function in vanilla JS?

I am trying to redirect to another page after I receive a response from the post fetch, but as the title says it doesn't work.
These are the functions:
// send/post json
async function postData(json_data, api_path) {
const response = await fetch(api_path, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: json_data,
redirect: 'follow'
});
console.log("postData response: ", response);
return response;
}
// send JSON data to server on /api/${destination}
function saveSettings(form, destination) {
let json_data = toJSONstring(form);
let res;
console.log(json_data);
postData(json_data, `/api/${destination}`)
.then((response) => {
res = response;
if (!response.ok) {
throw new Error(`HTTP error, status = ${response.status}`);
}
return response.text();
}).then(text => {
if (destination === 'network/post') {
connected = false;
updatingToast(`You are no longer connected to the device !`, false);
updatingToast(`Please navigate to ${text}`, true, text);
}
console.log('res: ', res);
res.redirect(res.status, res.url);
});
}
Every console.log(); returns Response {type: 'basic', url: 'http://192.168.0.100/dashboard', redirected: true, status: 200, ok: true, …}
If I place response.redirect(response.status, response.url); in the first then() I get the same error.
So, does response.redirect exist in Vanilla JS ?
I don't want to use window.location.href or any other similar option because it bypasses HTTP Authentication header.
I see that you have the 'follow' argument given in the fetch.
You can check the if the response is being redirected using the code below. If it was not redirected you can simply change the window location and also force a redirect.
if (res.redirected) {
window.location.href = res.url;
}
EDIT:
After doing a bit more research into the redirect method I saw that you need to switch the URL and status variables, see: https://developer.mozilla.org/en-US/docs/Web/API/Response/redirect

Passing request parameters on an API fetch Request

How do I pass down parameters to a fetch request? I have this api call to fetch the logged in users username. How do I pass the returned results to the other fetch request route as it's request parameter?
//Gets logged in user's username
async function getProfile(){
try {
const response = await fetch(`${SUMMIT_API}/users/myprofile`,{
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${myToken}`
},
})
const data = await response.json();
console.log(data)
return data.profile
} catch (error) {
console.log('Oops Something Went Wrong! Could not get that user profile.');
}
}
Results from above fetch:
//Request parameters is the logged in user's username in the route retrieved from above fetch request
async function userChannel(){
try {
const response = await fetch(`${SUMMIT_API}/users/myprofile/**${username}**/channel`,{
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${myToken}`
}
})
const data = await response.json();
console.log(data)
return data.profile;
} catch (error) {
console.log('Oops Something Went Wrong! Could not render userChannel');
}
}
How do I get the information from first request passed to the second?
Since the information you want seems to be supplied by your async function getProfile, it seems like you simply need to await getProfile() and pull the necessary information out:
var profile = await getProfile();
var username = profile[0].username;

Translating C# to Javascript

I am working on a project for a client and need to convert this api call to Javascript.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://stagingapi.asapconnected.com/api/login");
request.Headers.Add(HttpRequestHeader.Authorization, "user=username&organizationId=id&password=password&apiKey=apikey");
HttpWebResponse response = (HttpWebResponse)request.GetResponse()
string accessToken = response.Headers["asap_accesstoken"];
My attempt translated into AXIOS get request:
axios({
method: 'GET',
url: 'https://api.asapconnected.com/api/login'
headers: {
'Authorization': 'user=org***&password=*******&organizationId=*****',
}
}).then(res => {
console.log(res);
}).catch(err => {
console.log(err);
});
Keep getting an error:
OPTIONS https://api.asapconnected.com/api/login net::ERR_CONNECTION_RESET
Any suggestions?

Categories