无法在POST方法中的node.js中设置标头

时间:2011-06-29 11:03:16

标签: node.js response.write

我有一个案例,我必须从请求正文中读取数据并创建一个文件并将数据写入其中。如果操作成功,我将响应标头设置为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。除此之外,即使收到响应,服务器也总是很忙。

1 个答案:

答案 0 :(得分: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对象声明为使用.listen()函数实际侦听端口/ IP。

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

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

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

可以找到有关http对象的更多文档on the node.js documents for http