开发者

Unable to set headers in node.js in POST method

I have a case where i have to read the data from the request body and create a file and write the data into it. If the operation is successful I set the response header to 201 and add the location of file in Location header. The file creation is done using Java methods and node.js code is below.

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);                 开发者_如何学JAVA       
            if(rtn.length < 13)
            {
                res.writeHead(201, {"Location" : rtn});
                res.end();
            }
            else
            {
                res.writeHead(400, {"Content-Type" : application/json"});
                res.write(''+rtn);
                res.end();
            }

        }); 
}});

The problem is that the response headers are not getting updated and are always set to the default headers 200 Ok. In addition to this the server is always busy even after the response is received.


I don't think you're actually listening on a port with the code you reference.

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/');

You never declare the http object as actually listening on a port/ip with the .listen() function.

Also, you don't need to wait for the req object to emit anything to respond. The function is called when the request is complete. You can listen for specific requests and route them appopriately by storing the http.Server object to a variable.

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

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

More documentation on the http object can be found on the node.js documents for http

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜