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服务器。
转载于:https://www.cnblogs.com/zhoudaozhang/p/4704396.html