0

我有一个案例,我必须从请求正文中读取数据并创建一个文件并将数据写入其中。如果操作成功,我将响应头设置为 201,并在 Location 头中添加文件的位置。文件创建是使用 Java 方法完成的,node.js 代码如下。

var server = http.createServer(function(req, res)
    {
        var body = "";
        req.on("data", function(chunk)
        {
            body += chunk.toString();
        }); 

        req.on("end", function() {          
            var rtn = obj.AddonPostMethod(filepath,body);                        
            if(rtn.length < 13)
            {
                res.writeHead(201, {"Location" : rtn});
                res.end();
            }
            else
            {
                res.writeHead(400, {"Content-Type" : application/json"});
                res.write(''+rtn);
                res.end();
            }

        }); 
}});

问题是响应标头没有得到更新,并且始终设置为默认标头 200 Ok。除此之外,即使在收到响应后,服务器也总是很忙。

4

1 回答 1

0

我认为您实际上并没有使用您引用的代码在端口上侦听。

var http = require('http');
http.createServer(function(req,res){
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');

您永远不会使用该函数将 http 对象声明为实际侦听端口/ip .listen()

此外,您无需等待 req 对象发出任何响应。当请求完成时调用该函数。您可以通过将 http.Server 对象存储到变量来侦听特定请求并适当地路由它们。

var server = http.createServer();
server.listen(8000);

server.on('request', function(req,res){ /* do something with the request */ });

有关 http 对象的更多文档可以在 http的 node.js 文档中找到

于 2011-06-29T17:23:07.493 回答