CORS Error when running a pageView for ReactGA - reactjs

I am trying to add React-GA to a react web app and have followed the documentation by adding it to index.js:
import ReactGA from 'react-ga';
ReactGA.initialize('MY_ID');
ReactGA.pageview(window.location.pathname + window.location.search);
However, this results in the following error in the browser console
Access to XMLHttpRequest at
'https://www.google-analytics.com/j/collect?......'
from origin 'http://localhost:3000' 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'. The credentials mode of requests initiated by the
XMLHttpRequest is controlled by the withCredentials attribute.
analytics.js:37 POST
https://www.google-analytics.com/j/collect?......
net::ERR_FAILED
Looking at the Google Analytics HTTP response in the network tab, I am definitely seeing the wildcard set for access-control-allow-headers:
access-control-allow-credentials: true
access-control-allow-headers: *
access-control-allow-methods: GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS
access-control-allow-origin: *
access-control-expose-headers: *
...
However, I am not sure how to resolve this on my end since it appears to be caused by the response from Google.

I think your problem is that you are using a wildcard with a request with the credentials mode 'include'.
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'.
You need to specify the origin for your request to work. here is 'http://localhost:3000'.
You can find more information on this stackoverflow post
I used this code to test Google Analytics with 'create-react-app'.

Here is an example, using the ReactGa inside an userEffect, and initializing it with some userState variable example userId (optional) and marking cookieDomain as auto and enabling debug.
import ReactGa from 'react-ga';
useEffect(()=>{
ReactGa.initialize('Tracking_Id', {
gaOptions: {
userId: username ? username :'Not-Logged'
},
'cookieDomain': 'auto',
'debug': true
});
ReactGa.pageview(window.location.pathname + window.location.search)
console.log(ReactGa.ga())
},[])

You may be able to use the CORS anywhere proxy, by simply just requesting to https://cors-anywhere.herokuapp.com/https://www.google-analytics.com/j/collect?..... instead

Related

react - No 'Access-Control-Allow-Origin' header is present on the requested resource when fetching the images from s3

import imageToBase64 from 'image-to-base64';
...
formatImageToBase64 = () => {
imageToBase64("https://example.s3.ap-southeast-1.amazonaws.com/images/image1") // Path to the image
.then(
(response) => {
console.log(response);
}
)
.catch(
(error) => {
console.log(error);
}
)
}
When I run this function, error occurs as below.
Access to fetch at 'example.s3.ap-southeast-1.amazonaws.com/images/image1?AWSAccessKeyId=qwertyuip12344&Expires=1664366635&Signature=aoqogfjfj3%2Foofofol%3D' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled
I checked my S3 setting but it seems no problem.
I also tried to change the AllowedOrigin to '*', but still not working.
Try <AllowedOrigin>*</AllowedOrigin> instead of your localhost and check if it works - if it does then you know the problem is within AllowedOrigin rule.
For more detailed description how to define your CORS just take a look at: S3 - Access-Control-Allow-Origin Header
UPDATE: I've tried to access the link you've provided and what I've got in return is a following message "The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint".
You can follow it up at: AWS S3: The bucket you are attempting to access must be addressed using the specified endpoint

Enable the cors in opendsitro for elasticsearch

I installed opendistro for elastic search using docker and tried to fetch the information from opendistro kibana portal using react js, but I am getting an error about cors (Access-control-allow-origin):
Access to fetch at 'https://example.com/api/v1/auth/authinfo' from origin 'http://example.com:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
then added a few lines in elasticsearch.yml file:
opendsitro_security.http.cors.enabled : true
opendsitro_security.http.cors.allow-origin: "*"
opendsitro_security.http.cors.allow-methods: OPTIONS, HEAD, GET, POST, PUT, DELETE
opendsitro_security.http.cors.allow-headers: X-Requested-With,X-Auth-Token,Content-Type,Content-Length
opendsitro_security.http.cors.allow-credentials: true
but still, I am getting the same error. My doubt is there any other way to enable cors in opendsitro for elastic search.

Axios failing to downloand an image from s3 due to CORS

When making Axios GET call to retrieve an image from s3 bucket it creates a preflight check using OPTIONS method. Options method response includes the Access-Controll-Allow-Origin: * header with a wild card but the subsequent GET call fails to retrieve the image.
Browser console out put:
Access to XMLHttpRequest at 'https://example.com' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Response headers from the OPTIONS call:
Response headers from the subsequent GET call:
Axios config for the GET call:
Go to bucket permission and configure cors [https://docs.aws.amazon.com/AmazonS3/latest/userguide/ManageCorsUsing.html][s3 cors documentation]

How to How to fix "No 'Access-Control-Allow-Origin' header is present on the requested resource" in post call in reactJS using Fetch method

Getting below error while i call DotNet core API method from ReactJS post call using Fetch options.
ReactJS post call only i am getting this error, below way i was tried.
Jquery get/post request - working fine
Postman get/post request - working fine
Swagger get/post request - working fine
ReactJS get request - working fine
ReactJS post request - Not working fine
"Access to fetch at 'https://localhost:44352/api/Address/CheckAvailability' from origin 'http://localhost:3000' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."
/*ReactJS Code: */
export function saveAddress(address) {
return fetch(baseURL + "Address/CheckAvailability", {
method: "POST",
headers: {
"Access-Control-Allow-Origin": "*",
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(address),
}).then(handleResponse)
.catch(handleError);
}
/*Dot.Net core Code: */
[HttpPost]
public ActionResult CheckAvailability([FromBody]ReqAddressDetailsDto request)
{
if ((request) == null)
{
return NotFound();
}
return Ok(request);
}
If your client application (the React web app) is on another scheme (any of http/https, domain or port is different), you need to have CORS enabled on your ASP.NET Core back-end.
In the Startup.cs file, you need to add this:
In ConfigureServices()
services.AddCors(options =>
{
options.AddDefaultPolicy(builder =>
{
builder.WithOrigins("http://localhost:3000/")
.AllowAnyMethod()
.AllowAnyHeader();
});
});
In Configure() put this just before app.UseMvc():
app.UseCors();
Check this link for more info:
https://learn.microsoft.com/en-us/aspnet/core/security/cors
did you enabled / configured cors in this .net core api?
How to enable CORS in ASP.NET Core
You can check CORS headers on your backend script.
The CORS standard manages cross-origin requests by adding new HTTP headers to the standard list of headers. The following are the new HTTP headers added by the CORS standard:
Access-Control-Allow-Origin
Access-Control-Allow-Credentials
Access-Control-Allow-Headers
Access-Control-Allow-Methods
Access-Control-Expose-Headers
Access-Control-Max-Age
Access-Control-Request-Headers
Access-Control-Request-Method
Origin
These headers are all important, but let’s we focus on the following header:
Access-Control-Allow-Origin
You should define Access-Control-Allow-Origin header as '*'. I guess, it may be solved your problem simply. A little example for PHP:
<?php
header("Access-Control-Allow-Origin: *");
You may find an info of each CORS header the following: CORS Headers.
If you want to learn more details about CORS, You can follow this link.
This status code is a useful hint to understand that the server doesn’t support OPTIONS requests.
Add the corresponding header on the server side when handling the OPTIONS method. We will then have the following requests:
Access-Control-Allow-Headers : Content-type
Hopefully this solves .

Node JS CORS module not setting Access-Control-Allow-Credentials header

Am trying to set Access-Control-Allow-Credentials header globally in Node Js using the CORS module configuration like this
`var cors = require('cors');
var corsOptions = {
origin: true,
'Access-Control-Allow-Origin': 'localhost:1550'
'Access-Control-Allow-Credentials': 'true'
};
app.use(cors(corsOptions));`
This doesn't seem to work so I set it too for the route am trying to set a preflight response for. I set it like this
`router.options('/login', cors(corsOptions));`
I check on Chrome Developer Tools and I see Access-Control-Allow-Origin header is set but not Access-Control-Allow-Credentials. I need this header since I have set withCredentials = true in Angular.
Why is Node JS not setting Access-Control-Allow-Credentials header yet it sets the others?
I know this because am getting the following error in console
XMLHttpRequest cannot load http://www.localhost:1550/api/v1/auth/login. Response to preflight request doesn't pass access control check: Credentials flag is 'true', but the 'Access-Control-Allow-Credentials' header is ''. It must be 'true' to allow credentials. Origin 'http://127.0.0.1:1550' is therefore not allowed access.
I think you are not setting the configurations correctly. As in the documentation
https://www.npmjs.com/package/cors#configuration-options
var corsOptions = {
origin: 'localhost:1550',
credentials : true
}
this will set the credentials header. As Origin sets Access-Control-Allow-Origin and credentials sets Access-Control-Allow-Credentials.
You left out the details about what library if any you are using. Is it express? Post the full code.
Since you are just specifying the headers explicitly anyway you can drop the cors module.
You can adapt this answer
In Node.js/Express, how do I automatically add this header to every "render" response?

Resources