Why is AngularJS error message empty on error handling? - javascript

I am using the AngularJS code to make a request to the server. On success it works fine, but when I redirect the request to some other domain provoking the CORS problem intentionally, error handling function is invoked but errorData is empty. In Chrome when i debug I can see that error function is hit and also I get message "No 'Access-Control-Allow-Origin' header is present on the requested resource." in the console but I can not access it from code. How to log this error?
RemoteService.doRequestPromise().then(
function(resp) {
LEService.logIt(resp);
if (status != 200) {
LEService.error(resp);
}
},
function(errorData) {
LEService.error({ 'err': errorData });
}).finally(function() {
usSpinnerService.stop('spin1');
});

Here's what angular gives you for a failed CORS request:
{
"data": null,
"status": 0,
"config": {
"method": "GET",
"transformRequest": [
null
],
"transformResponse": [
null
],
"url": "https://some.site/thing",
"headers": {
"Accept": "application/json, text/plain, */*"
}
},
"statusText": ""
}
Nothing about CORS but you have a status of 0 and an empty statusText. There probably aren't many other scenarios where you'd receive a status of 0, but it's something worth putting more research into if you absolutely need to be sure that this is a CORS error.

Related

How do I get the response as json to display in the console log of a url using axios?

The code I am writing is attempting to console.log a random Wikipedia article URL using wikipedia's random article link. (https://en.wikipedia.org/wiki/Special:Random)
I am trying to use axios.get with the above URL and to return the response (which should include the randomly generated link) that the URL generates. (I would like to pinpoint on just console.logging this generated link and no other data, but that is the next step).
Here is the code I have written (in my app.html runner() is ran).
function run(){
axios.get("https://en.wikipedia.org/wiki/Special:Random", {
responseType: "json",
})
.then(function (response) {
console.log(response.data);
});
}
function runner(){
run()
}
I am getting these errors:
Access to XMLHttpRequest at 'https://en.m.wikipedia.org/wiki/Special:Random' (redirected from 'https://en.wikipedia.org/wiki/Special:Random') from origin '(it's classified)' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
,
GET https://en.m.wikipedia.org/wiki/Special:Random net::ERR_FAILED 302
(anonymous) # isAxiosError.js:12
e.exports # isAxiosError.js:12
e.exports # isAxiosError.js:12
l.request # isAxiosError.js:12
r.forEach.l.<computed> # isAxiosError.js:12
(anonymous) # isAxiosError.js:12
run # factbotprogram.js:20
runner # factbotprogram.js:29
(anonymous) # app.html:12
and
{
"message": "Network Error",
"name": "AxiosError",
"config": {
"transitional": {
"silentJSONParsing": true,
"forcedJSONParsing": true,
"clarifyTimeoutError": false
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1,
"env": {
"FormData": null
},
"headers": {
"Accept": "application/json, text/plain, */*"
},
"responseType": "json",
"method": "get",
"url": "https://en.wikipedia.org/wiki/Special:Random"
},
"code": "ERR_NETWORK",
"status": null
}
However, one thing I found: If I go to 'network' in dev tools there are 2 Special:Random Fetch/XHR entires, the second one is red. Only if I click on that red one and look in it's 'Response Headers' do I get the information I am looking for, assigned to variable 'location' (this is the URL of a random wiki article). How do I pinpoint this and log, or assign to variable, just that 'location' url string?

Axios response returning empty string

axios.post(
'http://localhost:3001/users',
{
username:user.username
}
).then((res)=> console.log(res.data))
Response From FrontEnd : data: ""
Response i get from postman :
[
{
"Username": "john4",
"Password": "",
"Email": "",
"ProfileImg": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAM1BMVEXk5ueutLeqsbTn6eqpr7PJzc/j5ebf4eLZ3N2wtrnBxsjN0NLGysy6v8HT1tissra8wMNxTKO9AAAFDklEQVR4nO2d3XqDIAxAlfivoO//tEOZWzvbVTEpic252W3PF0gAIcsyRVEURVEURVEURVEURVEURVEURVEURVEURVEURflgAFL/AirAqzXO9R7XNBVcy9TbuMHmxjN6lr92cNVVLKEurVfK/zCORVvW8iUBnC02dj+Wpu0z0Y6QlaN5phcwZqjkOkK5HZyPAjkIjSO4fIdfcOwFKkJlX4zPu7Ha1tIcwR3wWxyFhRG6g4Je0YpSPDJCV8a2Sv2zd1O1x/2WMDZCwljH+clRrHfWCLGK8REMiql//2si5+DKWKcWeAGcFMzzNrXC/0TUwQ2s6+LhlcwjTMlYsUIQzPO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SgSWG8UqfrrIICzYYSJXRr9BSPbpNzw7gBjKjKOYI7ReIGqQRIap5+5MdjyvuDkExvGeXSlONWZAP3/AZBwJohU7QJRGU+cTVH18ELmRPNBmibW6MT/k1b0XhdkRBvyT6SB6EYv/GvhSmRNpGngRULsAlxMCGNXp7w3FfdEbTEEDdLI9TdIKRUzUesa3I461ER8cpNT7gMRhpKmYVS9ELOgCUQsa4SsulciKiLbY+AnHD8cpuhISsnxpamI84sbDq9qYJgf8wiiOBrC7Ml7M7ZECCqKoiiKoiiKoiiKoijv5AvJxlZRyNWWLwAAAABJRU5ErkJggg==",
"Followers": [],
"Following": [],
"__v": 0
}
]
im trying to post data and get a response from my server , the server is returning the right data when i use postman but when i use axios i get an empty string any help?
when i console.log(res)
{
"data": "",
"status": 205,
"statusText": "Reset Content",
"headers": {
"content-length": "2042",
"content-type": "application/json; charset=utf-8"
},
"config": {
"transitional": {
"silentJSONParsing": true,
"forcedJSONParsing": true,
"clarifyTimeoutError": false
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json"
},
"method": "post",
"url": "http://localhost:3001/users",
"data": "{\"username\":\"john4\"}"
},
"request": {}
}
You should handle your HTTP requests asynchronously with axios, utilizing async await. It just makes it so much cleaner.
Example:
const sendGetRequest = async () => {
try {
const response = await axios.post('http://localhost:3001/users', { username: user.username });
console.log(response.data);
} catch (err) {
// Handle Error Here
console.error(err);
}
};
Calling the function sendGetRequest() in this case will send the post request, get the response and console log the response. And since it is utilizing try catch, if something goes wrong, it will console log the error.
Also make sure that your axios is properly setup. The correct headers etc. to match whatever you have with postman.
The issue was on my backend i sent res.status(205).json(user) instead of res.status(208).json(user) which somehow bugged it and caused it to send no data.

How to handle sign up a user error while using Firebase REST API

I've been trying to sign up a user using Firebase Rest API using Node & Axios HTTP library.
I'm able to create a new user with email and password.
But when email already exists in the database or password is less than 6 characters, it doesn't show the proper errors.
It just returns Request failed with status code 400
Here is my code.
const config =
{
headers:
{
'Content-Type': 'application/json',
},
};
data = {
'email': "test#test.com",
'password': "password123",
'returnSecureToken': true
}
try
{
let signup = await axios.post('https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=API_KEY',data,config)
res.json(signup.data);
}
catch(err)
{
res.json(err);
}
Error I get.
{
"message": "Request failed with status code 400",
"name": "Error",
"stack": "Error: Request failed with status code 400\n at createError (/Users/user/NodeJS/FirebaseAuth/node_modules/axios/lib/core/createError.js:16:15)\n at settle (/Users/user/NodeJS/FirebaseAuth/node_modules/axios/lib/core/settle.js:17:12)\n at IncomingMessage.handleStreamEnd (/Users/user/NodeJS/FirebaseAuth/node_modules/axios/lib/adapters/http.js:244:11)\n at IncomingMessage.emit (events.js:327:22)\n at endReadableNT (_stream_readable.js:1224:12)\n at processTicksAndRejections (internal/process/task_queues.js:84:21)",
"config": {
"url": "https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=API_KEY",
"method": "post",
"data": "{\"email\":\"test#test.com\",\"password\":\"password123\",\"returnSecureToken\":true}",
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json",
"User-Agent": "axios/0.21.0",
"Content-Length": 75
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1
}
}
Expected error here is : Email already exists. But it doesn't return this error.
What could be the issue here ?
Thanks!
By default firebase doesn't return response in the error body but it can be extracted with.
console.log(err.response.data.error);
This is not mentioned in the official firebase docs.

Sendgrid integration with SAPUI5 app returns '400 Bad Request' on POST but works on Postman

I'm developing a cordova hybrid app that utilizes UI5 library. I need to be able to send as Email from the app so I decided to use Sendgrid API and, since I had issues with the NodeJS module, I'm creating an AJAX request. I've previously tested the request with Postman, being able to successfully send emails. But, as I tried to do the same request from the app, I've stumbled upon a status '400 Bad Request' without further information. Here goes the code snippet:
var settings = {
"async": true,
"crossDomain": true,
"url": "https://api.sendgrid.com/v3/mail/send",
"method": "POST",
"headers": {
"Content-Type": "application/json",
"Authorization": "Bearer [REDACTED]",
"cache-control": "no-cache"
},
"processData": false,
"data": {
"personalizations": [
{
"to": [
{
"email": "myemail#gmail.com"
}
],
"subject": "Contato do app"
}
],
"from": {
"email": "anotheremail#gmail.com"
},
"content": [
{
"type": "text/plain",
"value": formatEmail //variable with the email text
}
]
}
}
$.ajax(settings).then(
function success(response, status) {
dialog.close();
if (status == 202){
MessageBox.confirm('Mensagem enviada com sucesso', {
actions: [sap.m.MessageBox.Action.OK],
onClose: function(sAction){
that.onNavBack()
}
});
} else {
MessageBox.error('Erro!');
}
},
function fail(data, status){
dialog.close();
MessageBox.error('Request failed. Returned status of ' + status + ' DEBUGDATA: ' + JSON.stringify(data));
}
);
I really can't figure out the reason as to why this happens because the snippet generated by Postman is very similar to my code. Any help would be highly appreciated!
Thanks in advance
usually HTTP 400 means bad request and it means that you're passing the wrong parameters to the HTTP POST request.

Failed 401 Unauthorised error displayed in protractor

I am trying to automate the response which is getting generated in the postman tool but getting the error 401 unqutorized error. tried to resolve in many ways by giving the exact security token to the authorization-token but it didnt worked out.
//In this method the security token passed is newly generated and it works fine and produces response 200 in postman tool
async claimsetResponseOP(SecurityToken:string){
var options = {
method: 'POST',
url: 'http://nhsappchna8086/LMHIAService/api/v3/ValueSet/$expand',
//Giving header to the request
headers: {
'Authorization-Token': SecurityToken, // Here is the place where the security token is passed in the headers
'Accept': 'application/json+fhir',
'Content-Type' : 'application/json+fhir',
'Authorization-Type' : 'Native'
},
body: {
"resourceType ": "Parameters",
"parameter": [
{
"name": "ValueSet",
"resource": {
"resourceType": "ValueSet",
"status": "active",
"compose": {
"include": [{
"system": "http://snomed.info/sct",
"filter": [{
"property": "constraint",
"op": "=",
"value": "<<(*:R363698007=271629002)"
}
]
}
]
}
}
}
]
},
json:true,
resolveWithFullResponse: true
};
//Error gets displayed in below line as Failed 401 unautorized error
await requestp(options).then(async function(response){
await requestp(options).then(async function(Content){
if (await response.statusCode == 200){
var info = Content.body;
}
})
})
}
Below error gets displayed while executing: Can anyone please help in resolving
Failed: 401 - {"resourceType":"OperationOutcome","id":"AUTH-01","text":{"status":"additional","div":"Unauthorised"},"issue": [{"severity":"error","code":"security","details":{"text":"9254 - Unauthorised"}}]}
No. Manually when i run it is working fine.

Categories

Resources