Home > Web Front-end > JS Tutorial > Simple web server function example implemented by nodejs

Simple web server function example implemented by nodejs

亚连
Release: 2018-05-30 10:36:56
Original
1402 people have browsed it

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 in need can refer to it

The example in this article describes the simple web server function implemented by nodejs. Share it with everyone for your reference, the details are as follows:

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);
  }
});
Copy after login


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;);
Copy after login

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How to perfectly parse data in js

Solve the problem of failure after using vue.js routing

Example of the function of uploading pictures to the database and displaying them on the page implemented by vue

The above is the detailed content of Simple web server function example implemented by nodejs. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template