Build a simple query server using express.

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.