getting status -1 instead 401 Angularjs - javascript

I'm trying to get a response from server. The function looks so:
function getOverview() {
var req = {
method: 'GET',
url: base,
headers: {
'authorization': 'Bearer ' + GottenTokens.getSessionToken()
}
};
return $http(req).then(
function successCallback(response) {
return response;
}, function errorCallback(response) {
console.log(response);
return response;
});
}
When the status is 200, there's no problem, it returns the good response with status 200. But... when the status is 401, than it returns a response with status -1:
Object {data: null, status: -1, config: Object, statusText: ""}
I was trying it in postman and I saw there's the status 401 and also in browser it says so:
XMLHttpRequest cannot load http://localhost:5000/overview. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 401.
It means that the browser and postman take the status from server, but it doesn't come in Angularjs. I was trying this post: Capture Http 401 but it doesn't help me. I have that function in a "factory".
By the way, the server is written in akka. I don't know if it has something to do. Before was it in NodeJS and I didn't have problems. Since it's in akka I can't get the status in Angularjs.
Could anybody help me?

When doing cross-site requests, the server has to add to ALL responses a valid CORS header. This includes error responses like 401.
Make sure you can see the "Access-Control-Allow-Origin" header in your 401 response, it's most likely missing.

Related

Javascript fetch API returning opaque response [duplicate]

I tried to use this Cat Facts API like so:
const URL = "https://catfact.ninja/fact?limit=1" // In browser, this displays the JSON
fetch(URL).then(response=> {
console.log(response);
return response.json();
}
);
but I got
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://catfact.ninja/fact?limit=1. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
TypeError: NetworkError when attempting to fetch resource.
so after trying with
fetch(URL, {mode:'no-cors'})
.then(response=> {
console.log(response);
return response.json();
}
);
I now get
Response { type: "opaque", url: "", redirected: false, status: 0, ok: false, statusText: "", headers: Headers, body: null, bodyUsed: false }
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
I understand from here that I won't be able to use this API as intended. But if so, what is the purpose of it and how is it intended to be used (this info does not account for the issue)?
An opaque response is one you cannot see the content of. They aren't useful in of themselves.
Setting mode: 'no-cors' is a declaration that you don't need to read the response (or do anything else that requires CORS permission).
For example, the JavaScript might be sending analytics data to be recorded by a server.
The benefit of no-cors mode is that it lets you send the data without getting exceptions reported in the JS console (which would (a) look bad if anyone opened it and (b) flood the console with junk that makes it hard to find real errors).
If you need to access the response, don't set mode: 'no-cors'. If it is a cross origin request then you will need to use some other technique to bypass the Same Origin Policy.
Aside: "Access-Control-Allow-Origin": "*" is a response header. Do not put it on a request. It will do nothing useful and might turn a simple request into a preflighted request.
Adding {mode: 'no-cors'} is not a catch-all for CORS errors. You might be better off using a CORS Proxy.
This question might also be of use to you.
Alternatively, and depending on your needs, using a different API could be the easiest solution. I was able to return a cat fact from "https://meowfacts.herokuapp.com/". See below.
const URL = "https://meowfacts.herokuapp.com/"
async function getCatFact() {
const response = await fetch(URL)
console.log(await response.json())
}
getCatFact()

How do I resolve a cors error on a fetch or 401?

So I've been experiencing this CORS error and a 401 and have tried chrome plugins to allow for cors with no luck. Here are the errors I'm getting after disabling cors via the plugin:
Access to fetch at 'https://api.playground.klarna.com/payments/v1/sessions' from origin 'https://localhost' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
Failed to load resource: net::ERR_FAILED
Error: TypeError: Failed to fetch
Before enabling the CORS Chrome Extension I was receiving a Allow-Access-Control-Origin is not set on the first error message. Along with this in the network tab I'm getting a 401 Preflight which indicates unauthorized but I'm setting the Authorization header with the correct credentials so not sure what's happening here. I'm using the codeigniter php framework.
I'm using Basic auth with:
var auth = 'Basic ' + btoa(username:password);
Here's the code:
let postDataSession = {
"purchase_country" : bookingData.purchase_country,
"purchase_currency" : bookingData.purchase_currency,
"locale" : bookingData.locale,
"order_amount" : bookingData.order_amount,
"order_tax_amount" : 0,
"order_lines" : [{
//"type" : "physical",
"reference" : bookingData.order_lines.reference,
"name" : bookingData.item_name,
"quantity" : 1,
"unit_price" : bookingData.order_amount,
"tax_rate" : 0,
"total_amount" : bookingData.order_amount,
"total_discount_amount": 0,
"total_tax_amount" : 0
}]
};
fetch('https://api.playground.klarna.com/payments/v1/sessions', {
method: 'POST',
//mode: 'no-cors',
//Authorization: auth,
headers: {
'Content-Type': 'application/json',
'Authorization': auth,
//'Access-Control-Allow-Credentials' : true,
'Access-Control-Allow-Headers' : 'pm-u, pm-h0, pm-h1, pm-h3, pm-o0, pm-o1, pm-o2, pm-o3, authorization',
'Access-Control-Allow-Methods': 'POST',
'Access-Control-Allow-Origin': 'https://localhost',
'ACCESS-CONTROL-MAX-AGE' : 3600,
'referrer-policy': 'no-referrer-when-downgrade'
},
body: JSON.stringify(postDataSession),
})
.then(function(response) {
//The following method initializes the Klarna Payments JS library
//window.location.href = baseurl + "customer/klarna_checkout_page";
if (!response.ok) {
return response.text().then(result => Promise.reject(new Error(result)));
console.log(response.status);
}
console.log(response.json(), response);
return response.json();
})
// .then(function(session) {
// window.location.href = baseurl + "customer/klarna_checkout_page";
// })
.then(function(result) {
// If `redirectToCheckout` fails due to a browser or network
// error, you should display the localized error message to your
// customer using `error.message`.
if (result.error) {
alert(result.error.message);
}
console.log(result);
})
.catch(function(error) {
console.error('Error:', error);
});
I've tried it the mode set to no-cors and receive the same response. I've used postman to post the request with the same data and in postman a response is received. Not sure if I'm either missing or overlooking something so a fresh perspective would be helpful. Does anyone have any idea how to proceed with resolving this issue? I want to avoid having to deploy this code to the live domain and be able to test the response on localhost, not sure if that's at all possible with cors.
Browser extensions are notoriously useless at dealing with preflighted requests. It won't help here.
No-cors mode makes the browser silently fail anything that requires CORS permission instead of throwing an exception. It won't help here.
Postman isn't a browser. It's requests aren't triggered by visiting a website. It doesn't implement the Same Origin Policy and doesn't need permission from CORS.
I'm getting a 401 Preflight which indicates unauthorized but I'm setting the Authorization header with the correct credentials so not sure what's happening here.
The browser is making a preflight request asking permission to send a POST request with credentials.
The server is getting the preflight request and complaining that it doesn't have credentials on it.
Either:
Change the server you are making the request to so it grants you permission in your development environment. It needs to allow OPTIONS requests without credentials on them.
Use a proxy that relays your requests to the server
Is your backend .net core web services? If so, I have seen this problem when you call UseCors after UseAuthentication in your pipeline. If you do that, you will need an authenticated token to do the preflight which is why you get a cors error throwing the exception. Move UseCors to before UseAuthentication so that a CORS response does not have to go through the Authentication middleware first.

Unable to make LinkedIn API calls from localhost with Axios

I am trying to access linkedin profile using axios get request, which doesn't work on localhost and I get the following error
XMLHttpRequest cannot load
https://api.linkedin.com/v1/people/~:(id,email-address)?format=json.
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:8030' is therefore not allowed
access. The response had HTTP status code 401.
I am able to get access-token using react-linkedin-login package, after getting the access token I am trying the following code
var linkedInUrl = `https://api.linkedin.com/v1/people/~:(id,email-address)?format=json`;
var headers = {
'Authorization': `Bearer ${accessToken}`,
'Access-Control-Allow-Methods':'GET,PUT,PATCH,POST,DELETE',
'Access-Control-Allow-Origin':'*',
'Access-Control-Request-Headers':'Origin, X-Requested-With, Content-Type, Accept',
'Content-Type':'application/x-www-form-urlencoded'
};
return (dispatch) => {
axios.get(linkedInUrl, {headers}).then(({data}) => {
console.log(data);
}, (error) => {
console.log(error);
});
}
The problems lies in linkedin server how it takes request I guess, it doesn't allow localhost to make call I think. How to overcome this to actually develop the service before I deploy and run on server.
Thanks for helping..
This is because of a browser restriction called the "Same-origin Policy", which prevents fetching data from, or posting data to, URLs that are part of other domains. You can get around it if the other domain supports Cross-origin Resource Sharing (CORS), but it looks like LinkedIn doesn't, so you may have trouble.
One way around this is to have a web service which can proxy your request to LinkedIn - there's no domain restrictions there.
https://en.wikipedia.org/wiki/Same-origin_policy
https://en.wikipedia.org/wiki/Cross-origin_resource_sharing
try jsonp for CORS request - reference - axios cookbook
var jsonp = require('jsonp');
jsonp(linkedInUrl, null, function (err, data) {
if (err) {
console.error(err.message);
} else {
console.log(data);
}
});
EDIT
Use jQuery to perform JSONP request and to set headers
$.ajax({url: linkedInUrl,
type: 'GET',
contentType: "application/json",
headers: header, /* pass your header object */
dataType: 'jsonp',
success: function(data) {
console.log(data);
},
error: function(err) {
console.log('Error', err);
},
});
https://cors-anywhere.herokuapp.com/ - Add this before the url and it will work

Response to CORS preflight has HTTP status code 405

This is pretty much a known standard error but unable to fix the same using existing Stackoverflow posts.
XMLHttpRequest cannot load https://myserver.com/context/
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested
resource.
Origin 'https://www.otherwebsite.com' is therefore not allowed access.
The response had HTTP status code 405.
Following is the code I have -
function setHeader(xhr) {
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
}
var url = "https://myserver.com/context/";
$.ajax({
url: url,
type: 'GET', dataType:'json',
success: function(data) {
_this.question(data.question);
_this.questionId(data.questionId);
_this.choices(data.choices);
}, error: function() {
console.log("ERROR in getting microquestion");
},
beforeSend: setHeader
});
The “Response to preflight request… had HTTP status code 405.” message indicates, to start, the https://myserver.com/context/ endpoint needs to be configured to handle OPTIONS requests correctly—even if it may already be set to send the right CORS headers back for “normal” requests.
For more details about what’s happening, you can read the How to avoid the CORS preflight section of the answer at No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API — but the gist of it is, minimally, the server must respond to OPTIONS requests with a 2xx success status code.

does reCaptcha work in localhost?

does it?
Everything is working fine, until I send the user response to the google server to verify. This is the code that sends the response:
$http({
method: "get",
url: "https://www.google.com/recaptcha/api/siteverify",
params: {
secret: 'my-secret-key',
response: $scope.response
}
}).success(function (response) {
console.log(response);
}).error(function (errResponse) {
console.log(errResponse)
});
Then, I am getting this:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access.
Yes it works, but you can't send ajax/http requests to validate captcha from js. Yous should write your own backend function which will send this request.
Something like this:
Getting response from captcha with js callback (as you already did)
Send ajax request with captcha response to your own server
From your server send request with response and secret key to https://www.google.com/recaptcha/api/siteverify
Return response to your ajax function.

Categories