美文网首页
js bug: Origin 'null' is therefo

js bug: Origin 'null' is therefo

作者: 大乔是个美少女 | 来源:发表于2018-04-27 20:37 被阅读0次

先说一下问题的由来,在本地html页面ajax请求本地或者局域网server的资源时遇到的bug,先来段出问题的代码:

<script type="text/javascript">
    $.ajax({
        type:"get",
        url:"http://192.168.199.59:9000/api/v1/questions/5825acefffa2f815acdb03cf",
        success:function(res){
            console.log(888);
        },
        error:function(){
            console.log(66666)
        }
    });
</script>

翻译一下大家的解释好了:
Origin null is not allowed by Access-Control-Allow-Origin 意味着你在尝试ajax请求本地文件,因为安全的原因,这是被禁止的。
服务端的做法是在response内允许这么做:

response.setHeader("Access-Control-Allow-Origin", "*")

如果Chrome浏览器的话可以尝试加入新的插件:
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi/related

来个参考文献
Chrome Origin null is not allowed by Access-Control-Allow-Origin

PS
有些朋友可能会发生这样的问题,你的get方法可以跨域但是post方法不行,然后在浏览器的console里面你会看到有我们很少用的option请求,这种问题最明确的问题就是你的服务端也许并有一个叫做option的路由,加一个就好了,例如:

OPTIONS          /*url                  controllers.Application.options(url: String)

相关文章

网友评论

      本文标题:js bug: Origin 'null' is therefo

      本文链接:https://www.haomeiwen.com/subject/fvbilftx.html