繁体   English   中英

可以使用单个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?

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

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

如果是这样,最简单的方法是什么(我很高兴使用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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM