Node: Web applications built using the Express

I. Introduction

We use the http in front of the service to create a simple web application that provides a framework in nodeJs in to create a web service, this framework is to express. express node of one web frame is used to construct a web server can express, by the web server accepts the request req, and processing the web in response res.

 

Second, the application

1, likewise create a node project

2, create and launch a express service

// introduced express frame 
const express the require = ( ' express ' ) 

// create a service instance express 
const App = express (); 

// receiving a request and response process 
app.use ((REQ, RES) => { 
    res.json ( { 
        name: " xiayuanquan " , 
        Age: 28 
    }) 
}); 

// set listening 
app.listen ( 3000 , () => { 
    the console.log ( " Server started successfully! " ); 
})

3, open a browser to access HTTP: // localhost: 3000 / , or use Postman debugging request, the results were as follows.

 

Third, the request

在上面使用了express服务的use函数来接收请求和处理响应,发现不论是刷新浏览器还是使用Postmain进行请求,其响应的结果都能获取到。express还可以使用get和post进行指定路径的请求,如下所示:

//引入express框架
const express = require('express')

//创建express服务实例
const app = express();

//get请求: http://127.0.0.1:3000/name
app.get('/name', (req, res) => {
    res.send('xiayuanquan get');
});

//post请求: http://127.0.0.1:3000/age
app.post('/age', (req, res) => {
    res.send('28 post');
})

//设置监听
app.listen(3000, ()=>{
    console.log("server 启动成功!");
})

使用浏览器访问http://127.0.0.1:3000/name结果如下: 【浏览器默认使用的都是get请求】

使用Postman的get请求访问http://127.0.0.1:3000/name结果如下: 【如果此时使用Posetman的post请求,无法获取请求结果】

使用浏览器访问http://127.0.0.1:3000/age结果如下: 【浏览器默认使用的都是get请求,所以请求失败】

使用Postman的post请求访问http://127.0.0.1:3000/age结果如下: 【如果此时使用Posetman的get请求,无法获取请求结果】

 

四、传参

使用express也支持在请求时,将参数拼接到路径后面进行响应。如下所示:

//引入express框架
const express = require('express')

//创建express服务实例
const app = express();

//get请求: http://127.0.0.1:3000/student1
//需要在该路径后面拼接上name和age这两个参数,例如:http://127.0.0.1:3000/student1/xiayuanquan/28
app.get('/student1/:name/:age', (req, res) => {
    //对参数进行析构
    let {name, age} = req.params;
    //将结果响应成json
    res.json({
        name,
        age
    })
});

//post请求: http://127.0.0.1:3000/student2
//需要在该路径后面拼接上name和age这两个参数,例如:http://127.0.0.1:3000/student2/zhangsan/30
app.post('/student2/:name/:age', (req, res) => {
    //对参数进行析构
    let {name, age} = req.params;
    //将结果响应成json
    res.json({
        name,
        age
    })
})

//设置监听
app.listen(3000, ()=>{
    console.log("server 启动成功!");
})

使用Postman的get请求路径http://127.0.0.1:3000/student1/xiayuanquan/28的结果如下:

使用Postman的post请求路径http://127.0.0.1:3000/student2/zhangsan/30的结果如下: 

 

Guess you like

Origin www.cnblogs.com/XYQ-208910/p/12115633.html