How to fix blocked redirect due to CORS issues? - javascript

Here is my setup:
Running a local angular application on port 4200
Running an API using Deno on port 4300.
I have a use case where a client call at some api endpoint http://localhost:4300/foo, needs to redirect the user to another portion of the front end, say http://localhost:4200/bar#baz.
Currently this fails with the following error:
Access to XMLHttpRequest at 'http://localhost:4200/bar#baz' (redirected from 'http://localhost:4300/foo') from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
I have tried disabling/allowing cors on the API:
ctx.response.headers.set('Acces-Control-Allow-Origin','*');
ctx.response.headers.set('Acces-Control-Allow-Headers','*');
ctx.response.headers.set('Acces-Control-Allow-Methods','*');
ctx.response.headers.set('Access-Control-Allow-Credentials','true');
But this does not work.
Any ideas on how to fix this? Without setting up a proxy or installing a browser plugin.
Thanks!

See MDN:
The value "*" only counts as a special wildcard value for requests without credentials (requests without HTTP cookies or HTTP authentication information). In requests with credentials, it is treated as the literal header name "*" without special semantics. Note that the Authorization header can't be wildcarded and always needs to be listed explicitly.
You are making a request with credentials therefore you can't use * as a wildcard and have to be explicit about which headers you are using.

Related

Access-Control-Allow-Origin and handling from localhost

So, in my React app, I am making some endpoint calls to different servers and I also have withCredentials set to true, since I pass some token/cookie along with all the requests.
Now, how can I make this work on localhost seamlessly? Since I have withCredentials to true, the
Access-Control-Allow-Origin needs to have specific origin and cannot have * (so if host is localhost:3000, it is not allowed and I get CORS error)
Any ideas on making this work both for local testing and for env deployments?
Create a list of origins that are allowed to access each environment. Select a means to store this data apropriate for your backend environment.
In your server-side code, read the Origin request header and compare it to the list of allowed origins for the environment you are running in. If it matches one of them, add an Access-Control-Allow-Origin header with that value to the response.
For example, if you are using Node.js then:
Using .env.environmentName files is a common way to provide environment specific data.
The cors middleware will accept an array of allowed origins for the origin configuration option and will compare the Origin header to them and generate the right Access-Control-Allow-Origin header.

CORS error caused due to a web API(access-control-allow-origin)

I have been trying to use a web API in javascript but I repeatedly keep getting this error:
Access to fetch at
'https://eodhistoricaldata.com/api/fundamentals/AAPL.US?api_token={token}'
from origin 'http://127.0.0.1:5500' has been blocked by CORS policy:
The 'Access-Control-Allow-Origin' header has a value
'https://eodhistoricaldata.com/*' that is not equal to the supplied
origin. Have the server send the header with a valid value, or, if an
opaque response serves your needs, set the request's mode to 'no-cors'
to fetch the resource with CORS disabled.
How should I resolve this? I installed a plugin to set the desirable header but others can't install the plugin to view data.
Perhaps this is what you meant, but it's the HTTP response from your API at 'https://eodhistoricaldata.com/' that must include the Access-Control-Allow-Origin header in its HTTP responses.
If the value of that header is 'https://eodhistoricaldata.com/*', your web browser will trigger a CORS error if you call that API from code hosted in any domain other than 'https://eodhistoricaldata.com'. To fix this, you need to change the value your API returns for this header to the domain you want to allow to call your API.
Returning the value * for the Access-Control-Allow-Origin header will allow applications from any domain to call your API without a CORS error.

Frontend gets Error 401 from Backend in CORS request - apache/php insufficiently configured?

I have a frontend, running on most recent vue on port 5000.
Then I have my backend, running on most recent lumen on port 8080.
Both are on my localmachine. Later in production, they will be separated on two virtual machines.
Right now, when sending an http request from the frontend to the backend, I get the following error to my devConsole (NOT the vue devtools, but the usual firefox/chrome devtools console!):
Error: Request failed with status code 401
The function returning the axios object executing the http request looks like this:
function fetchData(method, slug, payload) {
return axios[method](`${API_ENDPOINT}${slug}`, payload);
}
The call looks like this:
fetchData(METHOD_POST, USER_LIST, "someToken").then((res)=>{
return res
})
METHOD_POST contains the string post and USER_LIST contains the string /user/show_data which is used to further specify the URL. In my Lumen backend, it accesses the following route:
$router->group(['prefix' => 'user', 'middleware' => 'auth'], function() use ($router){
$router->post('/show_data', 'UserController#getData');
});
The route and the respective controller work, I've tested it with RESTClient https://addons.mozilla.org/de/firefox/addon/restclient/
I think that syntaxwise, everything is fine. Also, the token wasnt expired when I used it, I checked this multiple times.
So I think that it might be connected to the CORS-Policy of the apache and/or php.
Im running apache and php from the latest XAMPP dist.
Still, I'm not entirely sure if thats it, especially since this is the first time that I connect a backend using lumen and a frontend using vue.js.
EDIT: I managed to activate "withCredentials" for my axios object by changing the function body to:
axios.defaults.headers.withCredentials = true;
return axios[method](`${API_ENDPOINT}${slug}`, payload);
However, now the CORS problem turns up ^^
When sending the http request, I get these error messages to my console:
Access to XMLHttpRequest at 'http://localhost:8080/user/show_data' from origin 'http://localhost:5000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
And
xhr.js:178 POST http://localhost:8080/user/show_data net::ERR_FAILED
And
createError.js:16 Uncaught (in promise) Error: Network Error
at t.exports (createError.js:16)
at XMLHttpRequest.d.onerror (xhr.js:83)
What should I do?
EDIT2:
I now added the following lines to my httpd.conf and restarted apache and lumenproject:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Max-Age: 360
Header set Access-Control-Allow-Credentials: true
Header set Access-Control-Allow-Methods: *
Header set Access-Control-Allow-Headers: Origin
Header set Access-Control-Expose-Headers: Access-Control-Allow-Origin
</IfModule>
I also tried out explicitely specifying the origin to
http://localhost:8080
and
http://localhost:5000
But it didnt help. The errormessage remains the same.
Most browser will block you anyway if your backend allow any host.
Access-Control-Allow-Origin "*"
You are also missin a semi-colon
Access-Control-Allow-Origin: "*"
Try
Access-Control-Allow-Origin: "yourorigindomain.com"

javascript: fetch blocked by CORS policy because of wildcard

I am trying to use the following api endpoint using fetch:
https://api.guerrillamail.com/ajax.php?f=check_email&ip=${ip}&agent=${agent}
(outdated documentation)
When I set credentials: 'include' I get the following error:
Access to fetch at 'https://api.guerrillamail.com/ajax.php?...' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
I have to set the flag in order to submit a cookie for authentication.
After googling this problem for 1++ hour, my understanding is the following:
CORS has to be server side allowed to be able to make "none simple" request to an other domain e.g. localhost => guerrillamail.com to prevent abuse, a variable Access-Control-Allow-Origin has to be set to the domains that should be allowed to send requests. A valid option is "*", which means that ALL origins are ok.
For some reason it is not ok though in combination with the credentials: 'include flag.
Do you have any ideas why this wouldnt be allowed?
Do you know what I have to do, in order to to do the request?
And is my understanding about this correct?
The documentation you're referencing no longer applies. In that old documentation, the API was made available over HTTP rather than HTTPS. CORS doesn't apply to HTTP and wouldn't have been a problem.
In the latest documention, that API is provided over HTTPS. To deal with the CORS requirement, they also removed the need for cookies, changing it to subscr_token and sid_token parameters sent as part of the request:
version 1.5, 30th May 2011
- Removed the requirement for cookies, added subscr_token and sid_token parameters

CORS request in react

Getting this error when trying to get stuff from the Twitter API using simple-twitter:
XMLHttpRequest cannot load https://api.twitter.com/1.1/statuses/user_timeline.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:3000' is therefore not allowed access. The response had HTTP status code 400
I'm basically doing exactly what it says in the react docs, but with the relevant line replaced:
componentDidMount: function() {
twitter.get('statuses/user_timeline', function(error, data) {
if(this.isMounted()){
this.setState({tweets: data})
console.dir('callback')
}
}.bind(this));
}
The callback function seems to never fire, which I assume is due to the request not completing.
What am I missing here?
The issue here is the module you're using is written for Node, not the browser.
Whilst in the browser, you can't make requests outside of your origin (in this case localhost:3000) unless the requested resource is served with the appropriate Access-Control-Allow-Origin header.
In this case the browser makes a preflight (OPTIONS) request to the same resource to see whether the CORS checks pass and it can safely respond. In this case it can't because Twitter's API doesn't allow your origin.
You can avoid these limitations if the API supports JSONP, but as of V1.1 of the Twitter API, only OAuth is supported.
This means that to access the Twitter API from the client, you'll need to authenticate inside your session, in order to generate an OAuth token that you can use to make requests. Take a look at the codebird-js library.
Alternatively, you can use the simple-twitter module from a server and forward requests from your browser on to the Twitter API.

Categories

Resources