cors – WordPress: console errors from web sites I have linked to

On this one page of my site, https://litchfieldmagazine.com/litchfield-county-design-resource-guide/

I have hundreds of console errors that are coming from sites I have linked to in the posts displayed on the page. Security errors, iframe warning, font warnings etc.

I know what to do if these were errors on my site, but why am I getting errors about content that is not even on my site, but is on someone else’s that I have just hyperlinked to?

I have never seen anything like this before.

html – RequireJS and Cors problem

Just having
<script data-main="js/main" src="js/require.js"></script>
in an html page, and trying to open it (with valid main.js and require.js), in Firefox this raises

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///home/levis/tests/main.js. (Reason: CORS request not http)

How can I make it work locally please ?

rest – I get CORS error in Sharepoint but i also changed web-config. Nothing happens?

I call ajax request and the browser got CORS error. I tried to add "Access-Control-Allow-Origin" in IIS, webconfig. But it doesn’t work. I have two servers. My ajax is true only i have this issue. So how can i do that?

<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,OPTIONS" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Credentials" value="true" />

How to enable url in different domain, I get CORS policy error when calling ajax query in Sharepoint 2013

How to enable url in different domain, I get CORS policy error when calling ajax query in Sharepoint 2013

I did my ajax call properly, also i saw the results Internet Explorer. It works fine. But Edge, Chrome are blocking the url. I want to enable this url. Also we have two servers in the system. So what do you offer to me?

    $.ajax({
        type: "GET",
        url: myurl,
        cache: false,
        cors: true,
        headers: {
            'Access-Control-Allow-Origin': '*',
            "Content-Type": "text/json; charset = utf-8"
        },
        success: function (data) {
            console.log(data);
            $(data).find('ArrayOfString').each(function () {
                $(this).find("string").each(function () {
                    emailAddress += $(this).text() + ";";
                });

            });

        },
        error: function (a, b, c) {
            console.log(a);
            alert("Error");
        }
    });

In ASP.NET core – not adding a CORS middleware is causing a “Failed to load resource: net::ERR_CONNECTION_REFUSED” error

The question is asked by running two simple experiments. The observation from these experiments are a bit puzzling to understand. Could someone please help me make sense out of it?

Experiment 1:

  • Create a simple asp.net core api application with one end point https://localhost:5001/hello
  • Create a html page, that hits the end point on load
  • Run the asp.net core application
  • Open the html page in a browser and observer the console

Observation 1:

  • The empty html page loads
  • There is an error in the console saying “Failed to load resource: net::ERR_CONNECTION_REFUSED”
  • While checking the network tab of the browser, the GET call has failed.
  • There has been no OPTIONS call

Experiment 2:

  • Modify the asp.net core application to add a any origin cors policy
  • Use the cors policy
  • Run the asp.net core application
  • Open the html page in a browser and observer the console

Observation 2:

  • The empty html page loads
  • There is NO error in the console saying “Failed to load resource: net::ERR_CONNECTION_REFUSED”. The page is successfully able to access the resource from asp.net core application
  • While checking the network tab of the browser, the GET call has succeeded.
  • There has been no OPTIONS call

Doubt

  1. Why is adding CORS affecting this behavior. As per the CORS specification, simple get is not affected by CORS.
  2. Even if CORS is supposed to affect this. The behavior is not as per the CORS specification. There has been no OPTIONS call. The call that’s failing is GET

asp.net core code

HelloController.cs

    (ApiController)
    (Route("(controller)"))
    public class HelloController : ControllerBase
    {
        (HttpGet)
        public string Hello()
        {
            return "hello";
        }
    }

StartUp.cs

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            //********************************************
            //Enabled for the second experiment
            services.AddCors(c =>
            {
                c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
            });
            //********************************************
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            //***************************************
            //Enable for the second experiment
            app.UseCors("AllowOrigin");
            //****************************************

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }

HTML Code page.html

<html>
  <body onload="updateDB();">
  </body>
  <script language="javascript">
    function updateDB() {
      var xhr = new XMLHttpRequest();
      xhr.open("GET", "https://localhost:5001/hello", true);
      xhr.send(null);
    }
  </script>
</html>

firebase – Cors Policy Error when sending Authentication Bearer token – node.js (Google cloud functions)

I am trying to communicate to my cloud function from a chrome plugin. Everything works fine if i don’t enable authentication in the cloud function console. But when i enable only authenticated user then I get the following error
Access to XMLHttpRequest at 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.

My Ajax code

 return new Promise((resolve, reject) => {

    $.ajax({
      url : API_ENDPOINT+'method4',
      method : 'POST',
      beforeSend: function (xhr) {
          xhr.setRequestHeader('Authorization', 'Bearer '+firebase.auth().currentUser._lat);
      },
      data : 'id='+id,
      success: function(data, textStatus, xhr) {
          console.log(data);
          resolve(data);
      },
      error: function(data, textStatus, xhr) {
          reject(data);
          console.log(data)
      },
  });

});

Below is my Function code deployed on cloud function

exports.method4 = functions.https.onRequest((request, response) =>{


response.set('Access-Control-Allow-Origin', 'chrome-extension://pcpjkilopmjdhcigjjndndibccdingcb');
response.set('Access-Control-Allow-Credentials', 'true');

if (request.method === 'OPTIONS') {

  // Send response to OPTIONS requests
  response.set('Access-Control-Allow-Methods', 'GET, POST');
  response.set('Access-Control-Allow-Headers', 'Authorization');
  response.set('Access-Control-Max-Age', '3600');
  response.status(204).send('');

} else {

  if (request.method !== 'POST') {
    // Return a "method not allowed" error
    return response.status(405).end();
  }

  return response.send(request.body('id'));

}

})

I am stuck with this for the past 2 days and not sure what is causing this issue. Thanks in advance.

.htaccess – CORS Header allow cross origin not working for google fonts

Here I have some code in my .htaccess file

<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"

Header set X-UA-Compatible "IE=edge"

# `mod_headers` cannot match based on the content-type, however,
# the `X-UA-Compatible` response header should be send only for
# HTML documents and not for the other resources.

<FilesMatch ".(appcache|atom|bbaw|bmp|crx|css|cur|eot|f4(abpv)|flv|geojson|gif|htc|ico|jpe? 
g|js|json(ld)?|m4(av)|manifest|map|mp4|oex|og(agv)|opus|otf|pdf|png|rdf|rss|safariextz|svgz? 
|swf|topojson|tt(cf)|txt|vcard|vcf|vtt|webapp|web(mp)|webmanifest|woff2?|xloc|xml|xpi)$">
 Header unset X-UA-Compatible
</FilesMatch>

</IfModule>

on the first line i have the Header set Access-Control-Allow-Origin “*” and it does not seem to be working for any browser except for chrome. I tried using this in my root .htaccess file as well as .htaccess file in app folder. Is there something i am doing wrong? Also I should add that I am using a css @font-face for these google fonts.

azure – Problem with CORS Policy when call to API with SPFx

have problem with CORS Policy. Get an error:

Access to fetch at ‘https://XXX.azurewebsites.net/api/protocols’ from origin ‘https://localhost:4321’ 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 removed custome headers but an error still occurs.

const httpClientOptions: IHttpClientOptions = {
  headers: new Headers(),
  method: "GET",
  mode: "cors"
};
    
export default class ProtocolsWebPart extends BaseClientSideWebPart<IProtocolsWebPartProps> {

  public render(): void {
   

    this.domElement.innerHTML = `
      <div class="${ styles.protocols }">
        <div class="${ styles.container }">
          <div class="${ styles.row }">
            <div class="${ styles.column }">
               <div>${this.getJsonData()}</div>
            </div>
          </div>
        </div>
      </div>`;
  }

  public getJsonData = () => {
    this.context.httpClient
    .get('https://integroprotocolsapp.azurewebsites.net/api/protocols', HttpClient.configurations.v1, httpClientOptions)
    .then((response: HttpClientResponse) : Promise<any> => {
      console.log(response);
      return response.json();
      
    })
    .then((response: any): void => {
      console.log(response);
    });

Do you have any idea how to avoid CORS Policy in this case?

php – Problemas con el Protocolo CORS

Tengo un problema a la hora de realizar una peticion a un servidor externo.
La cuestion es que hace ya algún tiempo solucione este problema, pero ahora mismo desconozco si PHP ha actualizado sus librerias y el metodo que yo utilizo está desactualizado:

La peticion que realizo es mediante jQuery usando $.get a un php de otro servidor, esperando que me devuelva un json.

Codigo jQuery (js):

$.get ( 'https://example.com/data', { lang : lang }, function ( d ) {}, 'json' );

donde la variable lang es solo un parametro para indicar el idioma:

El código PHP del otro servidor:

<?php
    
    date_default_timezone_set ('Europe/Madrid');
    header ('Content-Type: application/json');
    header ('Content-Disposition: inline; filename="country.json"');
    header ("Cache-Control: no-cache, must-revalidate");
    header ("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
    
    function cors () {
        // Allow from any origin
        if ( isset ($_SERVER('HTTP_ORIGIN')) ) {
            header ( "Access-Control-Allow-Origin: {$_SERVER('HTTP_ORIGIN')}" );
            header ( 'Access-Control-Allow-Credentials: true' );
            header ( 'Access-Control-Max-Age: 86400' );    // cache for 1 day
        }
        // Access-Control headers are received during OPTIONS requests
        if ( $_SERVER('REQUEST_METHOD') == 'OPTIONS' ) {
            if ( isset( $_SERVER('HTTP_ACCESS_CONTROL_REQUEST_METHOD')) )
                header ( "Access-Control-Allow-Methods: GET, POST, OPTIONS" );         
            if ( isset ( $_SERVER('HTTP_ACCESS_CONTROL_REQUEST_HEADERS')) )
                header ( "Access-Control-Allow-Headers: {$_SERVER('HTTP_ACCESS_CONTROL_REQUEST_HEADERS')}" );
            exit(0);
        }
    }
    
    cors ();
    
    if ( !isset ( $_GET ('lang') ) ) { $lang = 'en'; } else { $lang = $_GET ('lang'); }
    
    $dir = scandir ( __DIR__ . '/lang/' );
    $isLang = 0;
    
    foreach ( $dir as $k => $v ) {
        
        if ( $v == $lang . '.php' ) { $isLang++; }
        
    }
    
    if ( !$isLang ) { $lang = 'en'; }
    
    require __DIR__ . '/lang/' . $lang . '.php';
    require __DIR__ . '/lang/info.php';
    
    if ( isset ( $_GET ('country') ) ) {
        
        echo json_encode ( ($_GET ('country') => $_l ($_GET ('country'))) );
        
    } else {
        
        echo json_encode ( $_l );
        
    }
    
?>

Esta formula de CORS ya la usé una vez en el pasado y me funcionó, pero por alguna razón ya no me funciona.
Javascript me devuelve el siguiente error:

jq:1 Access to XMLHttpRequest at ‘https://example.com/data?lang=es’ from origin ‘https://sample.com’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

jq:2 GET https://example.com/data?lang=es net::ERR_FAILED

Si alguien pudiese explicarme cual es el error o que es lo que esta fallando se lo agradeceria.
Muchas gracias.

security – Does the same site cookie policy potentially change anything for CORS

According to the new same-site cookie policy (once implemented across all browsers) , a third party call from another page would not send along the cookies by default, unless the third party explicitly indicates that by setting appropriate cookie metadata.

As per my understanding, this would help with CSRF prevention. Does it cover all cases for CSRF ? Can this policy obsolete the same-origin policy since it seems to solve the same problems, or does the same origin policy cover other use cases?
Does this potentially mean that we wouldn’t need CORS setup on the servers anymore?