node. JS environment Self-built, refer to the Novice tutorial node. js.
1 submitting form forms in index.html via Ajax
The register.html file is as follows:
<!DOCTYPE HTML><HTML><Head> <MetaCharSet= "UTF-8" /> <title>Document</title> <Scriptsrc= "Jquery.js"></Script> <Scriptsrc= "Ajax.js"></Script> <style>form{padding:100px;Border:1px solid Red;width:350px;margin:0 Auto;}Form Input{Display:Block;margin:0 Auto;Margin-bottom:20px;} </style></Head><Body> <formID= "Register"Action=""Method= "Get"> <inputtype= "hidden"name= "Action"value= "Register" />with Households Name:<inputtype= "text"name= "Name"placeholder= "Please enter user name ..." />Dense  Code:<inputtype= "Password"name= "Pass"placeholder= "Please enter password ..." />e-mail:<inputtype= "Email"name= "Email"placeholder= "Please enter a valid message name ..." /> <inputID= "Register-sub"type= "Submit"value= "Register" /> </form></Body></HTML>
The Ajax.js file is as follows:
$(function(){ $(' #register-sub '). On (' click ',function(){ varInfo = $ (' form '). Serialize (); $.ajax ({type:"Get", URL:"http://127.0.0.1:8081", Data:info, success:function(RESPONSE,STATUS,XHR) {alert (response); Localstorage.name= $ (' input[name= ' name "] '). Val (); } }); return false; }); $(' #login-sub '). On (' click ',function(){ return false; });});
2 focus node. JS Background : Receive data, write to database, return information to foreground
First create the server file: Server.js:res.writeHead (); the one behind is for cross-domain access
varHTTP = require (' http ');varurl = require (' URL '));varUtil = require (' util '));varMySQL = require ('./mysql ');//This is the file that I wrote to write the user to the database.Http.createserver (function(req,res) {Res.writehead (200,{"Content-type": ' Text/plain ', ' CharSet ': ' Utf-8 ', ' access-control-allow-origin ': ' * ', ' Access-control-allow-methods ': ' Put,post,get,delete,options '}); //Parsing URL Parameters varparams = Url.parse (Req.url,true). Query; Mysql.reg (Params.action,params.name,params.pass,params.email); Res.write ("Registered successfully"); Res.end ();}). Listen (8081);
Next Mysql.js File connection database:
Exports.reg =function(action,name,pass,email) {varMySQL = require (' MySQL '); varConnection =mysql.createconnection ({host:' localhost ', User:' Root ', Password:' 123456 ', Port:' 3306 ', Database:' Test ', }); Connection.connect (); varModsql = "INSERT into user (Name,pass,email) VALUES ('" "+name+" ', ' "+pass+" ', ' "+email+" ') "; Connection.query (Modsql,function(err, result) {if(Err) {Console.log (' [UPDATE ERROR]-', Err.message); return; } }); Connection.end ();}
In fact, a registration function is basically implemented, in the browser open register.html, click on the registration, the data will be submitted to the server (here cross-domain Austrian), and then write to the database, the implementation of the registration function.
node. js Front and back interaction example-Implementing user registration with node. js