[nodejs] get post

2021/10/28 11:10:35

本文主要是介绍[nodejs] get post,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

get

const http = require('http');
const url = require('url');

const host = 'http://localhost:3000';
http.createServer(function (req, res) {
  const { searchParams } = new URL(req.url, host);
  console.log(searchParams);
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end(searchParams.toString());
}).listen(3000);

console.log(`Server running at ${host}`);

 

post

login.ejs

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <form action="/doLogin" method="post">
    用户名:<input type="text" name="username"><br>
    密码: <input type="password" name="password"><br>

    <input type="submit" value="提交">
  </form>
</body>
</html>

server.js

const http = require('http');
const ejs = require('ejs');

const host = 'http://localhost:3000';
http.createServer(function (req, res) {
  const { url } = req;
  if (url === '/login') {
    ejs.renderFile('./login.ejs', {}, (err, data) => {
      if (!err) {
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.end(data);
      }
    })
  } else if (url === '/doLogin') {
    let postData = '';
    req.on('data', (chunk) => {
      postData += chunk;
    });
    req.on('end', () => {
      console.log(postData);
      res.end(postData);
    });
  }
  
}).listen(3000);

console.log(`Server running at ${host}`);

 



这篇关于[nodejs] get post的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程