k@M0me’s Humble Abode      博  客   时 间 线   归  档 



Node.js
Published on Sun Sep 12 2021 12:00:01 GMT+0000

Node.js 服务端开发

使用express搭建基础服务器并处理请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//initialize
const Port = 3000;//设置端口号,一般是3000
const express = require('express');
const { fstat } = require('fs');
const app = express();
process.env.PORT = Port;
app.use(express.static('public'))//allow browser access resources

//err catch
process.on('uncaughtException',function(err){}) //监听未捕获的异常
process.on('unhandledRejection',function(err,promise){}) //监听Promise没有被捕获的失败函数

//传送文件的方法
app.get('/borrow', (req, res) => {
res.setHeader('Content-Type','text/html');
res.sendFile('public/borrow/borrow.html',{ root : __dirname});
//由于sendFile要求使用绝对地址,所以要将根目录设置为当前文件夹
})

app.listen(Port, () => console.log('服务器已就绪,运行在端口'+Port))//输出服务器启动信息

基本的请求处理方式(以数据库为例):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//database
const mysql = require('mysql');
let databaseConnection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '123456',
database: 'books',
port: 3306
});
databaseConnection.connect();

app.get('/userinfo/*', (req, res) => {
let info = req.url;
let infoS = info.split('/');
let user = infoS[2];

let returnUser;
let userSelect = 'SELECT name from users where ID = ' + user;
databaseConnection.query(userSelect, function (error, results, fields) {
if (error) throw error;
returnUser = results[0].name;
res.send(returnUser);
});

})

处理表单,返回token:

1
2
3
4
5
6
7
app.post('/test_postForm', function (req, res) {
let receivedForm = req.body;
console.log('表单已获取');
let token = receivedForm['user_name'];
let resUrl = '/userMain?token='+token;
res.redirect(resUrl);
});