1.express
Based on the nodejs platform, a fast, open and minimal web development framework, official website address (Chinese version) , official website address
1. Basic use
- Download express
npm install express --save
-
Introduce express module
let express = require('express');
-
Build service instance
// 构建服务实例 相当于 http.createServer(); let app = express();
-
Receive server request
// 当服务端收到 get请求 / 的时候,执行回调函数 app.get('/',(req,res) => { res.send('Hello World'); })
-
Binding port
// 绑定端口 相当于http.listen() app.listen(3000,()=> { console.log('server is running...'); })
-
Complete code
let express = require('express'); // 构建服务实例 相当于 http.createServer(); let app = express(); // 公开指定目录,则可以通过/public直接进行访问其文件夹内的内容,可以写多个,灵活使用 app.use('/public/',express.static('./public/')); // 当服务端收到 get请求 / 的时候,执行回调函数 app.get('/',(req,res) => { // 在express中可以直接通过req.query来获取查询字符串参数 console.log(res.query); // 还是可使用nodejs 这的write和end方法进行数据传输,只不过send方法可以根据发送内容自动添加Content-Type属性 res.send('Hello World'); }) // 绑定端口 相当于http.listen() app.listen(3000,()=> { console.log('server is running...'); })
If you access the content under other paths,
express框架
it will be processed by default404
, and related prompt information will be displayed. If you want to write the processing of requests under multiple paths, you can write multipleapp.get()
, you don't have to judge yourself like nodejs natively writes http services. At the same time, if you want to open the resources under a certain path, you can take the following code to configure// 公开指定目录,则可以通过/public直接进行访问其文件夹内的内容,可以写多个,灵活使用 // 第一个参数配置客户端能怎么样进行访问,第二个参数是服务器端相对于当前文件的文件路径 app.use('/public/',express.static('./public/'));