场景

Node的Web应用框架Express的简介与搭建HelloWorld:

https://mp.csdn.net/console/editor/html/106650798

注:

博客:
https://blog.csdn.net/badao_liumang_qizhi
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。

实现

GET请求的参数的获取

通过res.query获取

app.get('/',(req,res)=>{
    res.send(req.query);
})

完整示例代码

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

//创建网站服务器
const app = express();
app.get('/',(req,res)=>{
    res.send(req.query);
})

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})

运行项目,浏览器中输入带参数的请求url

 

 

POST请求参数的获取

Express中接受post请求参数需要借助第三方包 body-parser

首先在项目目录下打开终端输入

npm install body-parser

或者

cnpm install body-parser

 

 

然后在app.js中引入

const bodyParser = require('body-parser');

然后在创建路由时

//拦截所有请求
//extended:false 方法内部使用querystring模块处理请求参数的格式
//extended:true 方法内部使用第三方模块qs处理请求参数的格式
app.use(bodyParser.urlencoded({extended:false}))
app.post('/add',(req,res)=>{
  //接收post请求参数
  res.send(req.body);
})

完整示例代码

//引入express框架
const express = require('express');
const bodyParser = require('body-parser');
//创建网站服务器
const app = express();


//拦截所有请求
//extended:false 方法内部使用querystring模块处理请求参数的格式
//extended:true 方法内部使用第三方模块qs处理请求参数的格式
app.use(bodyParser.urlencoded({extended:false}))
app.post('/add',(req,res)=>{
  //接收post请求参数
  res.send(req.body);
})


app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})

为了测试post请求,在项目目录下新建post.html

<!DOCTYPE html>
<html>
<head>
    <title>Document</title>
</head>
<body>
    <form action = "http://localhost:3000/add" method="POST">
        <input type="text" name = "key"> 
        <input type="text" name = "value"> 
        <button type="submit">提交</button>
    </form>
</body>
</html>

在浏览器中打开post.html

 

 

输入内容点击提交

 

 

posted on 2020-07-15 23:38  霸道流氓  阅读(3028)  评论(0编辑  收藏  举报

Live2D