Simple web server function example implemented by nodejs, nodejsweb
This article describes the simple web server functions implemented by nodejs. We will share this with you 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: 'http: // 192.168.0.114: 8080', // server address type: 'post', timeout: 30, dataType: 'json', data: {"username": username, "password": password}, success: function (res) {console. log (JSON. stringify (res);}, err: function (err) {alert (err );}});
Nodejs code:
Var http = require ('http'); var url = require ('url'); var qs = require ('querystring'); http. createServer (function (req, res) {res. writeHead (200, {'content-type': 'text/plain; charset = UTF-8 ', 'access-Control-Allow-origin ':'*'}); if (req. method. toUpperCase () = 'get') {var query = url. parse (req. url, true ). query; // the received data res. end (JSON. stringify (query);} else if (req. method. toUpperCase () = 'post') {var postData = ''; req. on ('data', function (data) {postData + = data; // accepted data}); req. on ('end', function () {var query = qs. parse (postData); res. end (JSON. stringify (query); // returned data });}}). listen ('123', function () {console. log ('this is callback');}); console. log ('server is running ');
I hope this article will help you design nodejs programs.