An example of node building a server through express
This article mainly introduces node to build its own server through express. The editor thinks it is quite good. Now I will share it with you and give it as a reference. Let’s follow the editor and take a look.
Preface
In order to simulate the project online, we need a server to provide an API for us to call data. This time I used the express framework to write the API interface. All requests are made through ajax requests to the server to return data. This is the first time I use node to write a backend. It's basically like crossing the river by feeling for the stones. If there are any deficiencies in the article, please point them out.
Install express framework
Portal: express official
Then introduce the middleware that needs to be introduced. Node itself provides some libraries. We can reference it directly through require. For libraries that are not provided, we can also install them through manual npm.
##
var fs = require('fs'); 操作文件模块 var http = require('http'); http模块 var url = require('url'); 获取url信息模块 var qs = require('querystring'); 处理url参数模块 var path = require('path'); 文件路径模块 var bodyParser = require('body-parser'); 请求体对象化 (必须)否则后台无法解析前端发送的body内容
app.use(bodyParser.json()); // 访问静态资源文件 这里是访问所有dist目录下的静态资源文件 app.use(express.static(path.resolve(__dirname, '../dist'))) app.use(express.static('public')); // 因为是单页应用 所有请求都走/dist/index.html app.get('/', function(req, res) { const html = fs.readFile(path.resolve(__dirname, '../dist/index.html'), 'utf-8'); res.send(html) }); //处理请求跨域 app.all('*', function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); res.header("Content-Type", "application/json;charset=utf-8"); res.header("Access-Control-Allow-Headers", "content-type"); next(); });
Database connection
Here I assume that you have installed the mongodb database and enabled it successfully. Read the express tutorial carefully and you will find that the framework provides support for mongodb. Mongodb has many extension plug-ins to use the database, such as mongoose. Here we use mongoskin officially provided by express to link to the database.$ npm install mongoskin #####官方实例 var db = require('mongoskin').db('localhost:27017/animals'); db.collection('mamals').find().toArray(function(err, result) { if (err) throw err; console.log(result); });
##
var db = require('mongoskin').db('mongodb://localhost:27017/blog'); var ObjectId = require('mongodb').ObjectID;
The above code indicates that we successfully connected to the blog database and enabled the private ID. The objectID is the ID automatically added to the data generated by mongodb. It can be used directly. At this point, the database and server have been connected. Process the request sent by the front end
Process the get request
/** * 获取文章信息 */ app.get('/article/info', function (req, res) { >>> 获取请求参数 var arg = qs.parse(url.parse(req.url).query); var id = arg.id; >>> 链接数据库根据参数查找文档并返回 db.collection('articleList').find({ "_id": ObjectId(id)}).toArray(function(err, result) { if (err) throw err; console.log(result) res.end(JSON.stringify(result)) }); });
The above code implements the processing of a get request, and obtains the parameters of the url through the parameter module. The db is the connected database. Search the data table of 'articleList' based on the ID. After processing, return the data through res.end() to complete the response. Processing post requests
/** * 提交留言信息 */ app.post('/board/post', function (req, res) { >>>> 获取请求参数 var data = { date: req.body.date, name: req.body.name, content: req.body.content, time: req.body.time, position: req.body.position }; >>> 链接数据库并插入数据 db.collection('board').insert(data, function(err, result) { if(err) { res.end('Error:'+ err) } res.end('提交成功') }); });
The parameter acquisition of post request is different from get, which can be obtained directly through req.body The request body transmitted by the front end. Get parameters through js objects. Then perform database operations based on the parameters. At this point, the basic requests have been introduced. Let’s talk about how to handle common file operation requirements such as uploading images. Processing front-end file requests
In order to simplify the operation, we can introduce the multer module to process files, the code is as follows
var multer = require('multer'); var storage = multer.diskStorage({ //设置上传后文件路径,uploads文件夹会自动创建。 destination: function (req, file, cb) { cb(null, './public/uploads') }, //给上传文件重命名,获取添加后缀名 filename: function (req, file, cb) { var fileFormat = (file.originalname).split("."); cb(null, file.fieldname + '-' + Date.now() + "." + fileFormat[fileFormat.length - 1]); } }); //生成上传模块,让API调用 var upload = multer({ storage: storage }).single('file');
The above code has successfully introduced the file upload module. Through this module, we can quickly generate corresponding content. For specific usage methods, you can view the official documentation. After the preparation work is completed, use it in the project:
/** * 图片上传 */ app.post('/upload', function (req, res) { upload(req, res, function (err) { if (err) { console.log(err) return } console.log(req.file) res.end(JSON.stringify(req.file)) }) }); //图片上传到服务器 ,向客户端返回文件信息 比如文件的存储位置,之后就可以通过地址访问服务器的图片 /** * 图片删除 */ app.post('/image/delete', function (req, res) { fs.unlink(req.body.path, function(err) { if (err) { return console.error(err); } res.end("文件删除成功!"); }); });
To upload pictures here, we directly use the upload module that has been written before. When the interface requests When successful, the file has been uploaded successfully. If you need a preview process, you should not call the upload interface directly. Through the native node fs module, we can also delete and modify the added files. Going online and the history mode refresh problems encountered after going online
We can regard the online process as changing a computer to run the program. Here I use Alibaba Cloud server. Install a good environment on the cloud server, clone the project into it, install a permanent runtime library such as forever, start ~ ok, and your project will always run. If you need www access, you also need to buy a dns resolution and domain name to point to your server.
As mentioned above, if we run the project locally, it will basically be no problem. But it will be refreshed after the project goes online. Ala? ? 404 what the hell? Open Baidu and check. That's a lot of fire~~ History mode is enabled on the current end, and support for history must also be enabled on the backend. The express environment is as follows:
var history = require('connect-history-api-fallback'); var connect = require('connect'); /////// app.use(history());
Update code refresh~OK perfect! Summary
If you want to learn something well, you need long-term accumulation. As a front-end, some knowledge of server databases can not only help us better communicate with our brothers (back-end), but it is also like a fish in water for the front-end.
The above is the detailed content of An example of node building a server through express. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Solution: 1. Check the eMule settings to make sure you have entered the correct server address and port number; 2. Check the network connection, make sure the computer is connected to the Internet, and reset the router; 3. Check whether the server is online. If your settings are If there is no problem with the network connection, you need to check whether the server is online; 4. Update the eMule version, visit the eMule official website, and download the latest version of the eMule software; 5. Seek help.

What should I do if the RPC server is unavailable and cannot be accessed on the desktop? In recent years, computers and the Internet have penetrated into every corner of our lives. As a technology for centralized computing and resource sharing, Remote Procedure Call (RPC) plays a vital role in network communication. However, sometimes we may encounter a situation where the RPC server is unavailable, resulting in the inability to enter the desktop. This article will describe some of the possible causes of this problem and provide solutions. First, we need to understand why the RPC server is unavailable. RPC server is a

As a LINUX user, we often need to install various software and servers on CentOS. This article will introduce in detail how to install fuse and set up a server on CentOS to help you complete the related operations smoothly. CentOS installation fuseFuse is a user space file system framework that allows unprivileged users to access and operate the file system through a customized file system. Installing fuse on CentOS is very simple, just follow the following steps: 1. Open the terminal and Log in as root user. 2. Use the following command to install the fuse package: ```yuminstallfuse3. Confirm the prompts during the installation process and enter `y` to continue. 4. Installation completed

The role of a DHCP relay is to forward received DHCP packets to another DHCP server on the network, even if the two servers are on different subnets. By using a DHCP relay, you can deploy a centralized DHCP server in the network center and use it to dynamically assign IP addresses to all network subnets/VLANs. Dnsmasq is a commonly used DNS and DHCP protocol server that can be configured as a DHCP relay server to help manage dynamic host configurations in the network. In this article, we will show you how to configure dnsmasq as a DHCP relay server. Content Topics: Network Topology Configuring Static IP Addresses on a DHCP Relay D on a Centralized DHCP Server

In network data transmission, IP proxy servers play an important role, helping users hide their real IP addresses, protect privacy, and improve access speeds. In this article, we will introduce the best practice guide on how to build an IP proxy server with PHP and provide specific code examples. What is an IP proxy server? An IP proxy server is an intermediate server located between the user and the target server. It acts as a transfer station between the user and the target server, forwarding the user's requests and responses. By using an IP proxy server

What should I do if I can’t enter the game when the epic server is offline? This problem must have been encountered by many friends. When this prompt appears, the genuine game cannot be started. This problem is usually caused by interference from the network and security software. So how should it be solved? The editor of this issue will explain I would like to share the solution with you, I hope today’s software tutorial can help you solve the problem. What to do if the epic server cannot enter the game when it is offline: 1. It may be interfered by security software. Close the game platform and security software and then restart. 2. The second is that the network fluctuates too much. Try restarting the router to see if it works. If the conditions are OK, you can try to use the 5g mobile network to operate. 3. Then there may be more

Detailed explanation and installation guide for PiNetwork nodes This article will introduce the PiNetwork ecosystem in detail - Pi nodes, a key role in the PiNetwork ecosystem, and provide complete steps for installation and configuration. After the launch of the PiNetwork blockchain test network, Pi nodes have become an important part of many pioneers actively participating in the testing, preparing for the upcoming main network release. If you don’t know PiNetwork yet, please refer to what is Picoin? What is the price for listing? Pi usage, mining and security analysis. What is PiNetwork? The PiNetwork project started in 2019 and owns its exclusive cryptocurrency Pi Coin. The project aims to create a one that everyone can participate

How to install PHPFFmpeg extension on server? Installing the PHPFFmpeg extension on the server can help us process audio and video files in PHP projects and implement functions such as encoding, decoding, editing, and processing of audio and video files. This article will introduce how to install the PHPFFmpeg extension on the server, as well as specific code examples. First, we need to ensure that PHP and FFmpeg are installed on the server. If FFmpeg is not installed, you can follow the steps below to install FFmpe
