Build a simple query server using express.
This article describes how to use express to set up a simple query server. The details are as follows:
The technology stacks used include express and mysql.
Project Structure:
service--node_modules--app.js--query.js
App. js supports service calling and uses body-parser to process requests.
Query. js allows you to connect to and query databases.
The app. js code is as follows:
Var express = require ('express '); var query = require ('. /query') var bodyParser = require ('body-parser '); var cookieParser = require ('cookie-parser'); var app = express (); app. use (bodyParser. urlencoded ({extended: false}) // The returned object is a key-value pair. When extended is false, the value in the key-value pair is in the 'string' or 'array' format. If it is true, it can be of any data type. App. use (bodyParser. json () // cross-origin support app. all ('*', function (req, res, next) {res. header ("Access-Control-Allow-Origin", "*"); res. header ('access-Control-Allow-Methods ', 'Put, GET, POST, DELETE, options'); res. header ("Access-Control-Allow-Headers", "X-Requested-With"); res. header ('access-Control-Allow-headers', 'content-type'); next () ;}); // log on to the app. post ('/login', (req, res) => {var opts = req. body; query ("SELE CT * FROM 'v _ users' WHERE userAcount =? ", Opts. userName). then (result) => {var response = result [0]; if (opts. password! = Response. u_password) {return res. send ({errorCode: '000000', errorMsg: 'logon password error'})} // generate a simulated logtailken var logtailken = response. userAcount + Math. random () * Math. pow (10, 16) res. send ({logtailken: logtailken}) var server = app. listen (3000, () => {console. log ('success ')})
The query. js code is as follows:
(function() { var mysql = require('mysql'); // var session = require('cookie-session'); var query = (sql,key) => { var connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'root123', database: 'm_users' }); connection.connect() var promise = new Promise((resolve,reject)=>{ connection.query(sql,[key], function(error, results, fields) { if(error){ reject(error) }else{ resolve(results); } }); connection.end(); }); return promise; } module.exports = query;})()
Practice summary:
1. Entry-level usage of express and the usage of the body-parser and mysql plug-ins.
2. Try to use Inspector to debug the node program and implement debugger. by the way, I am more accustomed to using gulp for debugging.
3. The difference between Content-Type and the client-side's post interface is as follows:
Content-Type: application/json; charset = UTF-8 parameter placed in requestPayload
Content-Type: Do not set or place the application/x-www-form-urlencoded parameter in Form Data
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.