使用 AJAX 发布到 Node 服务器

Using AJAX to POST to Node server

本文关键字:Node 服务器 AJAX 使用      更新时间:2023-09-26

我今天才发现Node.js,我读了很多书,让我头疼。 我已启动并运行节点服务器。 我在节点服务器上还有一个写入文本文件的.JS文件。我希望只看到一个变量(名称)从我的 Javascript 应用程序传递到运行 Node 的服务器.js以便更新日志文件。 根据我所读到的内容,AJAX 是执行此操作的最佳方法。 有人可以通过一个小代码示例让我朝着正确的方向前进吗?

服务器运行节点上的文件代码.js

var fs = require('fs'), str = 'some text';
fs.open('H://log.txt', 'a', 666, function( e, id ) 
{
  fs.write( id, str + ',', null, 'utf8', function(){
  fs.close(id, function(){
  console.log('file is updated');
});

});});

这就是我如何做你提到的:

创建一个快速的http服务器,查看任何连接的请求变量,并获取传入的参数,并将其写入文件。

var http = require('http');
http.createServer(function (req, res) {
    var inputText = req.url.substring(1);
    processInput ( inputText );
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Completed.');
}).listen(1337, '127.0.0.1');

在这里编辑:当然,你仍然需要定义processInput是什么。

function processInput ( text )
{
    // What you had before
    var fs = require('fs');
    fs.open ('H://log.txt', 'a', 666, function (e, id )
    {
        fs.write ( id, text + ',', null, 'utf8', function() {
            fs.close(id, function() {
               console.log('file is updated');
            }
        }
    });
}

这样,当您向

127.0.0.1:1337/写

它会将单词"write"写入文件(如果 processInput 写入输入)。

另一种处理方法是在 URI 中使用参数。有关如何执行此操作的更多信息,请参见 nodejs api。

祝你好运!