server.js内容:
var http = require('http') ;
var server = http.createServer(function(req,res){
res.writeHeader(200,{
'Content-Type' : 'text/plain;charset=utf-8', // 添加charset=utf-8,
'Access-Control-Allow-Origin':'*',//跨域支持
'Access-Control-Allow-Methods':'*'//跨域支持
}) ;
res.end("Hello,NodeJS!") ;
}) ;
server.listen(8888) ;
console.log("http server running on port 8888 ...") ;
cmd命令:
node server.js
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<button class="btn-test">点击请求nodejs接口</button>
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('.btn-test').click(function(){
$.ajax({
url:'http://localhost:8888',//刚才的server.js提供的简单服务http接口
type:'GET',
success:function(result){
alert("接口返回数据内容:"+result);
}
});
});
});
</script>
</body>
</html>
执行结果:
https://www.leftso.com/article/239.html