Origin null is not allowed by Access-Control-Allow-Origin
Asked Answered
B

8

210

I have made a small xslt file to create an html output called weather.xsl with code as follows:

<!-- DWXMLSource="http://weather.yahooapis.com/forecastrss?w=38325&u=c" -->
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
exclude-result-prefixes="yweather"
xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="/">
    <img src="{/*/*/item/yweather:condition/@text}.jpg"/>
</xsl:template>
</xsl:stylesheet>

I want to load in the html output into a div in an html file which I'm trying to do using jQuery as follows:

<div id="result">
<script type="text/javascript">
$('#result').load('weather.xsl');
</script>
</div>

But I am getting the following error: Origin null is not allowed by Access-Control-Allow-Origin.

I've read about adding a header to the xslt, but I'm not sure how to do that, so any help would be appreciated, and if loading in the html ouput can't be done this way, then advice on how else to do it would be great.

Brendon answered 10/12, 2011 at 12:36 Comment(2)
Is that your actual load call? There's no path on it at all?Gingery
To allow local pages/html files (Origin: null) from file system to access external resources(different origins), those external resources should respond with "Access-Control-Allow-Origin": "*" in response header.Burgh
G
252

Origin null is the local file system, so that suggests that you're loading the HTML page that does the load call via a file:/// URL (e.g., just double-clicking it in a local file browser or similar).

Most browsers apply the Same Origin Policy to local files by disallowing even loading files from the same directory as the document. (It used to be that Firefox allowed the same directory and subdirectories, but not any longer.

Basically, using ajax with local resources doesn't work.

If you're just testing something locally that you'll really be deploying to the web, rather than use local files, install a simple web server and test via http:// URLs instead. That gives you a much more accurate security picture. Your IDE may well have some kind of server built in (directly or via an extension) that lets you just hit "run" in the IDE and have the server fired up and serving the file.

Gingery answered 10/12, 2011 at 12:45 Comment(6)
After I upload it I no longer get Origin null, but I am still getting "not allowed by Access-Control-Allow-Origin."Brendon
If the resource you're loading is as you've shown ($('#result').load('weather.xsl');), that shouldn't happen, because the request is clearly to the same origin. If you're trying to load from somewhere else (e.g., $('#result').load('http://somewhere.else/weather.xsl');), then you're running into the SOP again, but in a different way. Ajax requests are restricted to the same origin (see link in answer), or if you're using a CORS-enabled browser and the server supports CORs, the server can choose whether to allow the cross-origin request.Gingery
I changed the load url. Changing it back to the one in the question makes it load fine. Thanks for the helpBrendon
What is the simplest, quickest way to set up a simple web server? Would IIS be the simplest way here?Silurid
@CiaranG I ran python -m SimpleHTTPServer from a command line and then went to localhost:8000, worked for me. Python comes preinstalled with Mac OS X; you may need to install if using another OS.Preiser
For those coming across this later, Firefox no longer allows that limited access, after CVE-2019-11730.Fordo
R
224

Chrome and Safari has a restriction on using ajax with local resources. That's why it's throwing an error like

Origin null is not allowed by Access-Control-Allow-Origin.

Solution: Use firefox or upload your data to a temporary server. If you still want to use Chrome, start it with the below option;

--allow-file-access-from-files

More info how to add the above parameter to your Chrome: Right click the Chrome icon on your task bar, right click the Google Chrome on the pop-up window and click properties and add the above parameter inside the Target textbox under Shortcut tab. It will like as below;

C:\Users\XXX_USER\AppData\Local\Google\Chrome\Application\chrome.exe --allow-file-access-from-files

Hope this will help!

Responsory answered 7/11, 2012 at 3:20 Comment(7)
In Mac OS X, you can start Chrome with this option by opening a terminal, and typing in: /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --allow-file-access-from-files & Note the final & is just so you can continue using the Terminal and is not required. NOTE: If you close the terminal, it will close the Chrome window.Micheal
Did all that and closed and opened. still no go (Chrome 27.0.1453.116 m on XP)Meritocracy
I'm not being able to add this parameter under Windows 8..., anybody who knows how to do it?...Callery
I am running from a web server. What the heck? How can I figure out where it's loading local files?Juarez
When I try to add --allow-file-access-from-files to the target path I get an "....invalid" message, is htis solution still valid?Wobbling
while adding this line chrome giving error ....make sure path is correct and doesn't allow me to save the changesBurford
This doesn't work for me. So, I found this working - chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-securityOsrock
T
74

Just wanted to add that the "run a webserver" answer seems quite daunting, but if you have python on your system (installed by default at least on MacOS and any Linux distribution) it's as easy as:

python -m http.server  # with python3

or

python -m SimpleHTTPServer  # with python2

So if you have your html file myfile.html in a folder, say mydir, all you have to do is:

cd /path/to/mydir
python -m http.server  # or the python2 alternative above

Then point your browser to:

http://localhost:8000/myfile.html

And you are done! Works on all browsers, without disabling web security, allowing local files, or even restarting the browser with command line options.

Trapeziform answered 7/3, 2014 at 16:32 Comment(5)
python 3 equivalent on windows is: python -m http.server [<portNo>]Shikari
Python 3: python3 -m http.serverLecturer
Python 2 on Linux, choosing 8080 port (or any other you want): python -m SimpleHTTPServer 8080Sass
While this was cool, sadly it did not resolve my cors issue. Gawd, I wish I knew more about cors. Here is an upvote for at least something cool.Hartwig
needed a quick CORS test mechanism and this worked great thanks.Oran
M
1

I would like to humbly add that according to this SO source: https://mcmap.net/q/128840/-jquery-ajax-run-as-a-local-html-file-avoiding-sop-same-origin-policy, this kind of trouble is now partially solved simply by using the following jQuery instruction:

<script> 
    $.support.cors = true;
</script>

I tried it on IE10.0.9200, and it worked immediately (using jquery-1.9.0.js).

On chrome 28.0.1500.95 - this instruction doesn't work (this happens all over as david complains in the comments at the link above)

Running chrome with --allow-file-access-from-files did not work for me (as Maistora's claims above)

Maypole answered 20/8, 2013 at 15:10 Comment(0)
N
1

Adding a bit to use Gokhan's solution for using:

--allow-file-access-from-files

Now you just need to append above text in Target text followed by a space. make sure you close all the instances of chrome browser after adding above property. Now restart chrome by the icon where you added this property. It should work for all.

Norge answered 20/11, 2013 at 7:46 Comment(1)
The parameter was already presented by Ghokan Tank and finding out how to always have the Browser start with this parameter is not part of the question. Additionally, you cannot assume everyone uses Microsoft Windows.Blowup
M
0

I was looking for an solution to make an XHR request to a server from a local html file and found a solution using Chrome and PHP. (no Jquery)

Javascripts:

var x = new XMLHttpRequest(); 
if(x) x.onreadystatechange=function(){ 
    if (x.readyState === 4 && x.status===200){
        console.log(x.responseText); //Success
    }else{ 
        console.log(x); //Failed
    }
};
x.open(GET, 'http://example.com/', true);
x.withCredentials = true;
x.send();

My Chrome's request header Origin: null

My PHP response header (Note that 'null' is a string). HTTP_REFERER allow cross-origin from a remote server to another.

header('Access-Control-Allow-Origin: '.(trim($_SERVER['HTTP_REFERER'],'/')?:'null'),true);
header('Access-Control-Allow-Credentials:true',true);

I was able to successfully connect to my server. You can disregards the Credentials headers, but this works for me with Apache's AuthType Basic enabled

I tested compatibility with FF and Opera, It works in many cases such as:

From a VM LAN IP (192.168.0.x) back to the VM'S WAN (public) IP:port
From a VM LAN IP back to a remote server domain name.
From a local .HTML file to the VM LAN IP and/or VM WAN IP:port,
From a local .HTML file to a remote server domain name.
And so on.

Meg answered 28/1, 2020 at 23:38 Comment(0)
H
-1

You can load a local Javascript file (in the tree below your file:/ source page) using the source tag:

<script src="my_data.js"></script>

If you encode your input into Javascript, like in this case:

mydata.js:

$xsl_text = "<xsl:stylesheet version="1.0" + ....

(this is easier for json) then you have your 'data' in a Javascript global variable to use as you wish.

Hexa answered 3/3, 2020 at 2:22 Comment(1)
this is exactly the problem the OP was having. Your solution does NOT work.Photogrammetry
F
-1

Using Java Spring to run a web service, you need to add:@ServletComponentScan right above @SpringBootApplication in your auto-generated YouAppApplication.java file ( the one with the main() function ) and create a class with the following implementation:

@WebFilter("/*")
public class AddResponseHeaderFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // ...
    }

    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        httpServletResponse.addHeader("Access-Control-Allow-Origin", "null");

        httpServletResponse.addHeader("Access-Control-Allow-Credentials", "true");
         filterChain.doFilter(servletRequest, servletResponse);

    }

    @Override
    public void destroy() {
        // ...
    }
}

note that you can choose a different name for this class as soon as it implements Filter and has the @WebFilter annotation you can also provide a different wildcard than /* so this filter doesn't apply to every endpoint.
As specified by @Louis Loudog Trottier you need to add ...withCredentials = true; when creating your Ajax request for this to work.

Fachini answered 27/1, 2023 at 19:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.