XMLHttpRequest cannot load http://localhost:3000/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
上面是我學習nodejs中碰到的一個異常,下面有代碼以及解決方案。
1)js文件代碼
var http=require('http');
var querystring=require('querystring');
http.createServer(function(req,res){
var postData='';
req.setEncoding('utf8');
req.on('data',function(chunk){
postData+=chunk;
});
req.on('end',function(){
res.end(postData+"hehe");
});
}).listen(3000);
console.log("服務啟動。。。")
2)前端html頁面代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script src="jquery-1.8.3.js"></script>
<script type="text/javascript">
$(function(){
$("#test").click(function(){
$.ajax({
'url':'http://localhost:3000',
'method':'POST',
'data':{},
'success':function(data){
console.log(data);
}
});
});
})
</script>
</head>
<body>
<p id="test">click me</p>
</body>
</html>
這是一個簡單的ajax訪問nodejs服務器demo,我的服務運行在windows10系統上。
win鍵+R 輸入CMD 調出命令行工具,輸入:node -v 查看是否安裝了nodejs以及版本。
通過cd命令定位到js文件所在目錄,輸入:node js文件名 運行js文件
谷歌瀏覽器打開html文件點擊click me然后按F12發現上文所說錯誤。
解決思路,百度一下發現是ajax跨域訪問問題
在createServer方法里面第一行設置 res.setHeader('Access-Control-Allow-Origin', '*');
*號代表允許任何與的請求,當然實際生產環境不可能這么做。
你可以通過報錯提示找到被拒絕的域然后設置res.setHeader('Access-Control-Allow-Origin', '域名');
比如我在HBulider里面打開html文件是這樣設置res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8020');
在本地直接打開html文件可以這樣子設置res.setHeader('Access-Control-Allow-Origin', 'null');
http://wishing.vip/ 這是我的移動端博客網址,里面有很多H5的實例。
會java或者c#等服務端語言的可以對比下
nodejs搭建一個web服務的是多么簡單,不需要tomcat等http服務器,因為它內置了一個http服務器。