js bug: Origin 'null' is therefore not allowed access.
阿新 • • 發佈:2019-01-29
先說一下問題的由來,在本地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", "*")
PS
有些朋友可能會發生這樣的問題,你的get方法可以跨域但是post方法不行,然後在瀏覽器的console裡面你會看到有我們很少用的option請求,這種問題最明確的問題就是你的服務端也許並有一個叫做option的路由,加一個就好了,例如:
OPTIONS /*url controllers.Application.options(url: String)