2016-01-13 56 views
0

我试图发送HTTP POST使用参数一样{name: myname}错误:无法设置头发送之后(不包括快递和bodyparser)

后端代码:

var qs = require('querystring'); 

     ... 
     case "POST": 

      if(request.url === "/api/user/delete"){ 

       //response.end('{}'); 
       var body = ''; 
       request.on('data', function (data) { 
        body += data; 
        // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB 
        if (body.length > 1e6) { 
         // FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST 
         response.writeHead(413, {'Content-Type': 'text/plain'}).end(); 
         request.connection.destroy(); 
        } 
        else{ 
         response.writeHead(200, {"Content-Type": "application/json"}); 
         response.end(JSON.stringify(qs.parse(body))); 
        } 
       }); 
       request.on('end', function() { 
        // use POST 
        var POST = qs.parse(body); 
        console.log(POST); //log shows '{'{myname}':''}' i need output like {name:myname} 


       }); 
      } 
     ... 
+1

添加一张支票headersSent的'data'事件可以触发一次以上。 – robertklep

+0

那么,你打电话给'response.end(JSON.stringify(qs.parse(body)));'你的第一部分数据。下一个块会出错,因为你已经发送了响应。这是一种预期的行为。但没有“那种”部分。 – cviejo

回答

0

理想情况下,你应该送对end响应事件的请求,以避免重新发送响应,因为data事件可能发生多次。

如果你真的需要data发送事件本身response对象

request.on('data', function(data) { 
body += data; 
// 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB 
if (body.length > 1e6 && !response.headersSent) { 
    // FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST 
    response.writeHead(413, { 
    'Content-Type': 'text/plain' 
    }).end(); 
    request.connection.destroy(); 
} else if (!response.headersSent) { 
    response.writeHead(200, { 
    "Content-Type": "application/json" 
    }); 
    response.end(JSON.stringify(qs.parse(body))); 
} 
}); 
相关问题