zhiqingstudy

Be a young person with knowledge and content

What is express

Express It is a fast, open and simple web development framework based on Node.js platform. Popular understanding: The function of Express is similar to the http module built in Node.js. It is specifically used to create Web servers.

The essence of Express: it is a third-party package on the npm, providing a convenient way to quickly create a Web server.

What can Express do

For front-end programmers, the two most common servers are:

·Web site server: a server dedicated to providing external Web page resources.

·API interface server: a server that provides API interfaces to the outside world.

With Express, we can easily and quickly create Web servers or API interface servers.

Installation of Express

In the directory where the project is located, run the following terminal command to install Express into the project.

npm i express@4.17.1

Create a basic web server

// 1.导入Express
const express=require('express')
// 2.创建web服务器
const app = express()
// 4.监听客户端的GET和POST请求,并向客户端响应具体的内容
app.get('/user',(req,res)=>{
    // 调用express提供的res.send()方法,向客户端响应一个JSON对象
    res.send({name:'李白',age:20,gender:'男'})
})
app.post('/user',(req,res)=>{
    // 调用express提供的res.send()方法,向客户端响应一个文本字符串
    res.send('请求成功')
})
app.get('/',(req,res)=>{
    // 通过req.query可以获取到客户端发送过来的查询参数
    // 注意:默认情况下,req.query是一个空对象
    console.log(req.query)
    res.send(req.query)
})
// 注意:这里的:id是一个动态参数
app.get('/user/:id',(req,res)=>{
    // req.params是动态匹配到url参数,默认也是一个空对象
    console.log(req.params)
    res.send(req.params)
})
// 调用express.static()方法,快速的对外提供静态资源,
app.use('/public',express.static('./public'))  // 第一个参数可以指定静态文件的访问前缀
// 提供多个对外静态资源
app.use('/clock',express.static('./clock'))
// 3.调用app.listen(端口号,启动成功后的回调函数),启动服务器
app.listen(80,()=>{
    console.log('express server running at http://127.0.0.1')
})
comment
head sculpture
Code:
Related

The art of interpersonal communication and communication

A code of conduct that regulates and regulates interpersonal relationships

The importance of interpersonal relationships




Unless otherwise specified, all content on this website is original. If the reprinted content infringes on your rights, please contact the administrator to delete it
Contact Email:2380712278@qq.com

Filing number:皖ICP备19012824号