一个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服务器及其体系结构完全陌生。我目前正在构建一个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);
相关文章:
- Javascript在for循环中等待处理请求
- EmberJS:在成功处理请求时解决承诺
- Gmail API 返回 400 个带有批处理请求的错误请求
- 在处理请求工作时显示“正在处理”
- 如何使 node js Express 服务器并行处理请求
- 节点 JS Express 模块是否异步处理请求
- 使用 javascript 使用 fql 进行批处理请求
- 如果可能的话,我应该使用 angularjs $http服务来处理请求还是 jquery ajax
- Node.js中的批处理请求
- 使用javascript动态处理请求字符串
- 当处理请求发布ajax时,如何禁用该表单中的表单(用户无法检查、填写文本、选择下拉列表等)
- 无法处理请求,因为模式对话框或警报处于活动状态
- 如何在.MVC 3 Razor中只触发一个JavaScript函数,而不需要控制器处理请求
- Javascript AJAX待处理请求
- 在Spring中处理请求之前显示等待页面
- 基于已知键数组向Firebase DB发出批处理请求的最有效方法是什么?
- 错误的错误.GrailsExceptionResolver -在处理请求:[GET]时发生NullPointerExce
- Facebook JS批处理请求返回Null
- 即使在用户通过javascript导航离开后,ASP.NET是否仍能继续可靠地处理请求
- 如何正确处理请求-承诺错误