一个node.js服务器文件可以同时用于HTML页面和处理来自该页面的POST请求吗

Can a single node.js server file be used to both serve a HTML page and process POST requests from said page?

本文关键字:处理 请求 POST HTML 文件 服务器 js node 用于 一个      更新时间:2023-09-26

我对运行Web服务器及其体系结构完全陌生。我目前正在构建一个web应用程序,它有一个基于HTML的GUI,使用一些JavaScript来部分处理用户数据,然后将其作为POST请求发送到web服务器。

我的问题很简单:同一个node.js服务器是否可以用于HTML网页的服务和POST请求的处理,或者是否需要两个不同的"服务器"(即两个不同侦听器和端口)?

如果是,最简单的方法是什么(我很乐意使用Express.js)我当前的服务器文件如下:

var express = require('express'),
serveStatic=require('serve-static'),
mysql = require('mysql');
var app = express();
app.use(serveStatic(__dirname));
var port = 8080;
app.listen(port, function() {
  console.log('server listening on port ' + port);
});
app.post('/', function(req, res){
  console.log('POST /');
  console.dir(req.body);
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('thanks');
});

只需要条件为request.method == 'POST':的if else

 http = require('http');
 fs = require('fs');
server = http.createServer( function(req, res) {
console.dir(req.param);
if (req.method == 'POST') { //-- Here Process POST requests
         console.log("POST");
         var body = '';
         req.on('data', function (data) {
           body += data;
          console.log("Partial body: " + body);
         });
         req.on('end', function () {
            console.log("Body: " + body);
         });
         res.writeHead(200, {'Content-Type': 'text/html'});
          res.end('post received');
     }
 else
 {  //!!!----Here process HTML pages
    console.log("GET");
    //var html = '<html><body><form method="post" action="http://localhost:3000">Name: <input type="text" name="name" /><input type="submit" value="Submit" /></form></body>';
    var html = fs.readFileSync('index.html');
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(html);
 }
});
port = 3000;
host = '127.0.0.1';
server.listen(port, host);
console.log('Listening at http://' + host + ':' + port);