Home >Web Front-end >JS Tutorial >How to implement simple web server functions in nodejs

How to implement simple web server functions in nodejs

小云云
小云云Original
2018-03-16 09:11:201315browse

This article mainly introduces the simple web server functions implemented by nodejs, and analyzes the related monitoring, response, data processing and other operating techniques of nodejs to build a web server in the form of examples. Friends who need it can refer to it. I hope it can help everyone. .

Front-end js code:


<script src="jquery-1.12.1.js"></script>
<script type="text/javascript">
 $.ajax({
  url:&#39;http://192.168.0.114:3000&#39;,//服务器地址
  type:&#39;post&#39;,
  timeout:30,
  dataType:&#39;json&#39;,
  data:{
    "username":username,
    "password":password
  },
  success:function(res){
    console.log(JSON.stringify(res));
  },
  err:function(err){
    alert(err);
  }
});

nodejs code:


var http = require(&#39;http&#39;);
var url = require(&#39;url&#39;);
var qs = require(&#39;querystring&#39;);
http.createServer(function(req,res){
  res.writeHead(200,{&#39;Content-Type&#39;:&#39;text/plain;charset=UTF-8&#39;,&#39;Access-Control-Allow-origin&#39;:&#39;*&#39;});
  if(req.method.toUpperCase() == &#39;GET&#39;){
    var query = url.parse(req.url, true).query;// 接受的数据
    res.end(JSON.stringify(query));
  }else if(req.method.toUpperCase() == &#39;POST&#39;){
    var postData = &#39;&#39;;
    req.on(&#39;data&#39;,function(data){
      postData += data; //接受的数据
    });
    req.on(&#39;end&#39;,function(){
      var query = qs.parse(postData);
      res.end(JSON.stringify(query));//返回的数据
    });
  }
}).listen(&#39;3000&#39;,function(){
  console.log(&#39;this is callback&#39;);
});
console.log(&#39;server is running&#39;);


Related recommendations:

Tutorial on how to build a simple web server using node.js

The above is the detailed content of How to implement simple web server functions in nodejs. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn