【node】9、http服务获取到post数据

demo.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/heaven" method="post">
    用户名:<input type="text" name="user"><br>
    密码:<input type="password" name="psd"><br>
    <input type="submit">
</form>
</body>
</html>

post.js

const http = require('http') //开启服务
//url模块专门处理 https://www.baidu.com :8080/p/a/t/h?query=string#hash
const url = require('url')
const fs = require('fs')  //读取文件
//querystring专门处理user=qweqwe&psd=12312
const qs = require('querystring')

const server = http.createServer(function (req, res) {
  const { pathname } = url.parse(req.url, true)
  if (pathname === '/') {
    fs.readFile('./demo.html', function (err, data) {
      if (err) return
      res.end(data)
    })
  } else if (pathname === '/heaven') {
    console.log('表单的数据接受到了')
    //前端的post数据存放在请求体中的 并且是分批次传输
    var str = ''
    req.on('data', function (chunk) {
      str += chunk
    })
    req.on('end', function () {
      console.log(qs.parse(str)); //获取到post数据
      res.setHeader('content-type', 'text/html;charset=utf-8')
      res.end('数据响应完毕')
    })
  } else {
    res.setHeader('content-type', 'text/html;charset=utf-8')
    res.end('404')
  }
})

server.listen(3000, () => {
  console.log('3000端口已经启动了')
})

启动服务
在这里插入图片描述

浏览器发送post数据:
在这里插入图片描述

发布了218 篇原创文章 · 获赞 35 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/qq_41614928/article/details/102532403
今日推荐