运用express搭建一个简朴的查询服务器

运用到的手艺栈有express、mysql.
项目构造:

service
--node_modules
--app.js
--query.js

app.js支撑挪用效劳,运用body-parser对request举行处置惩罚.
query.js完成链接数据库以及查询数据库的功用.
app.js代码以下:

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 }))//返回的对象是一个键值对,当extended为false的时刻,键值对中的值就为'String'或'Array'情势,为true的时刻,则可为任何数据类型。
app.use(bodyParser.json())
//跨域支撑
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();
});
//登录
app.post('/login',(req,res)=>{
    var opts = req.body;
    query(" SELECT *FROM `v_users` WHERE userAcount = ?",opts.userName).then((result)=>{
        var response = result[0];
        if(opts.password !== response.u_password){
            return res.send({
                errorCode:'404',
                errorMsg:'登录暗码毛病'
            })
        }
        //模仿天生loginToken
        var loginToken = response.userAcount + Math.random()*Math.pow(10,16)
        res.send({
            loginToken:loginToken
        })
    })
})
var server = app.listen(3000,()=>{
    console.log('success')
})

query.js代码以下:

;
(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;
})()

实践总结:
1.express的入门级用法,以及对body-parser和mysql插件的用法。
2.尝试运用 Inspector调试node顺序,完成debugger,by the way 个人更习气运用gulp来调试.
3.客户端运用post调取接口的时刻要辨别Content-Type的区分:
Content-Type:application/json;charset=UTF-8 参数放在requestPayload
Content-Type:不设置或许application/x-www-form-urlencoded 参数放在Form Data

    原文作者:一只鱼
    原文地址: https://segmentfault.com/a/1190000013216440
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞