Cross-origin request for local file

后端 未结 4 1886
无人及你
无人及你 2021-01-11 12:35

I need to open a local html file in the browser. The javascript works fine but ajax stops working and XMLHttpRequest gives a cross origin error. Is there a way to run ajax f

相关标签:
4条回答
  • 2021-01-11 13:02

    If you are able to change the server code, you can try adding the string "null" to allowed origins. In Chrome, it sends the origin as "null" if it's running from a local file.

    Here's an example in ASP.NET Core for setting up the "null" origin:

    services.AddCors(options =>
    {
        options.AddPolicy("InsecurePolicy",
            builder => builder
                .WithOrigins("null")
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials());
    });
    

    Note that this is not recommended, but might be good enough if you just need it during development.

    0 讨论(0)
  • 2021-01-11 13:03

    The simplest way to allow this in Firefox is to navigate to about:config, look for the privacy.file_unique_originsetting and toggle it off.

    Essentially, Firefox used to treat local files from the same directory as being from the same source, thus CORS was happily satisfied. That behavior changed after CVE-2019-11730 was discovered.

    It worked fine for me on 84.0.1 on Arch. Just be sure to turn it off when not locally debugging.

    Source

    0 讨论(0)
  • 2021-01-11 13:10

    If you are using chrome, try this extension

    CORS allows web applications on one domain to make cross domain AJAX requests to another domain. It's dead simple to enable, only requiring a single response header to be sent by the server.

    What this extension does is add to response header rule - Access-Control-Allow-Origin: *

    You can do that manually also by sending a response header.

    For simple CORS requests, the server only needs to add the following header to its response: Access-Control-Allow-Origin: *

    Read this for more info.

    0 讨论(0)
  • 2021-01-11 13:21

    For anyone who wants to know, I had to run a server in the app to serve the js files. Seems like it's not possible to do it without running a server. If anyone knows of another way, do tell.

    0 讨论(0)
提交回复
热议问题