search
HomeWeb Front-endJS TutorialHow to build a query server in express

This time I will bring you how to build a query server with express. What are the precautions for express to build a query server? The following is a practical case, let’s take a look.

This article introduces the method of using express to build a simple query server and shares it with everyone. 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 calling services and using body-parser to process requests.

query.js implements the functions of linking to the database and querying the database.

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 }))//返回的对象是一个键值对,当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')
})

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, as well as usage of body-parser and mysql plug-ins.

2. Try to use Inspector to debugnode program and implement debugger, by the way. I am more accustomed to using gulp for debugging.

3.When the client uses post to call the interface, it must distinguish the difference of Content-Type:

Content-Type:application/json;charset=UTF-8 parameter is placed in requestPayload

Content-Type: is not set or application/x-www-form-urlencoded parameter is placed in Form Data ​​​​​

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Express multer implements the specific steps to upload node images

How vue operates static images and network images

The above is the detailed content of How to build a query server in express. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
在容器中怎么使用nginx搭建上传下载的文件服务器在容器中怎么使用nginx搭建上传下载的文件服务器May 15, 2023 pm 11:49 PM

一、安装nginx容器为了让nginx支持文件上传,需要下载并运行带有nginx-upload-module模块的容器:sudopodmanpulldocker.io/dimka2014/nginx-upload-with-progress-modules:latestsudopodman-d--namenginx-p83:80docker.io/dimka2014/nginx-upload-with-progress-modules该容器同时带有nginx-upload-module模块和ng

服务器怎么使用Nginx部署Springboot项目服务器怎么使用Nginx部署Springboot项目May 14, 2023 pm 01:55 PM

1,将java项目打成jar包这里我用到的是maven工具这里有两个项目,打包完成后一个为demo.jar,另一个为jst.jar2.准备工具1.服务器2.域名(注:经过备案)3.xshell用于连接服务器4.winscp(注:视图工具,用于传输jar)3.将jar包传入服务器直接拖动即可3.使用xshell运行jar包注:(服务器的java环境以及maven环境,各位请自行配置,这里不做描述。)cd到jar包路径下执行:nohupjava-jardemo.jar>temp.txt&

node项目中如何使用express来处理文件的上传node项目中如何使用express来处理文件的上传Mar 28, 2023 pm 07:28 PM

怎么处理文件上传?下面本篇文章给大家介绍一下node项目中如何使用express来处理文件的上传,希望对大家有所帮助!

vue3项目打包发布到服务器后访问页面显示空白怎么解决vue3项目打包发布到服务器后访问页面显示空白怎么解决May 17, 2023 am 08:19 AM

vue3项目打包发布到服务器后访问页面显示空白1、处理vue.config.js文件中的publicPath处理如下:const{defineConfig}=require('@vue/cli-service')module.exports=defineConfig({publicPath:process.env.NODE_ENV==='production'?'./':'/&

python中怎么使用TCP实现对话客户端和服务器python中怎么使用TCP实现对话客户端和服务器May 17, 2023 pm 03:40 PM

TCP客户端一个使用TCP协议实现可连续对话的客户端示例代码:importsocket#客户端配置HOST='localhost'PORT=12345#创建TCP套接字并连接服务器client_socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)client_socket.connect((HOST,PORT))whileTrue:#获取用户输入message=input("请输入要发送的消息:&

Linux怎么在两个服务器直接传文件Linux怎么在两个服务器直接传文件May 14, 2023 am 09:46 AM

scp是securecopy的简写,是linux系统下基于ssh登陆进行安全的远程文件拷贝命令。scp是加密的,rcp是不加密的,scp是rcp的加强版。因为scp传输是加密的,可能会稍微影响一下速度。另外,scp还非常不占资源,不会提高多少系统负荷,在这一点上,rsync就远远不及它了。虽然rsync比scp会快一点,但当小文件众多的情况下,rsync会导致硬盘I/O非常高,而scp基本不影响系统正常使用。场景:假设我现在有两台服务器(这里的公网ip和内网ip相互传都可以,当然用内网ip相互传

如何使用psutil模块获取服务器的CPU、内存和磁盘使用率?如何使用psutil模块获取服务器的CPU、内存和磁盘使用率?May 07, 2023 pm 10:28 PM

psutil是一个跨平台的Python库,它允许你获取有关系统进程和系统资源使用情况的信息。它支持Windows、Linux、OSX、FreeBSD、OpenBSD和NetBSD等操作系统,并提供了一些非常有用的功能,如:获取系统CPU使用率、内存使用率、磁盘使用率等信息。获取进程列表、进程状态、进程CPU使用率、进程内存使用率、进程IO信息等。杀死进程、发送信号给进程、挂起进程、恢复进程等操作。使用psutil,可以很方便地监控系统的运行状况,诊断问题和优化性能。以下是一个简单的示例,演示如何

Express和Laravel的对比分析:选择更适合你的框架Express和Laravel的对比分析:选择更适合你的框架Mar 10, 2024 pm 10:15 PM

Express和Laravel是两个非常流行的Web框架,分别代表了JavaScript和PHP两大开发语言的优秀框架。本文将针对这两个框架进行对比分析,帮助开发者选择更适合自己项目需求的框架。一、框架简介Express是一个基于Node.js平台的Web应用程序框架,它提供了一系列强大的功能和工具,使开发者可以快速搭建高性能的Web应用程序。Express

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.