download.js报跨域怎么解决?

请求本地的图片一直报这个错误Access to XMLHttpRequest at 'http://localhost/laravel/public/1.jpg' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
后来我换成一张后台已经允许跨域的网络图片还是报这个错误 怎么办?

代码如下

<html>
    <head>
        <meta charset="UTF-8">
        <title>Download Text File Demo</title>
        <style>
            body{ font: menu; }
        </style>
        <script src='https://js.zapjs.com/js/download.js'></script>
    </head>
    <body>
        <h1>Download Text File Demo</h1>
        <main></main>
        <script>
            var x=new XMLHttpRequest();
    x.open("GET", "http://localhost/laravel/public/1.jpg", true);
    x.responseType = 'blob';
    x.onload=function(e){download(x.response, "1.jpg", "image/jpeg" ); }
    x.send();
        </script>
    </body>

</html>
阅读 4.7k
1 个回答

应该是因为你本地环境导致的,你使用的是直接双击打开这个html文件吧,这个时候浏览器地址栏的地址会是类似:file:///xxx/index.html,这个时候是没有域的,所以你的报错信息是:from origin 'null',建议你将文件放在服务器环境下访问,类似:localhost://xxx/index.html,这个时候如果你设置的Access-Control-Allow-Origin*后者http://localhost的话,应该就不会报错了。

推荐问题