在服务器上调用两次post请求方法。为什么这样?

时间:2014-11-27 07:22:38

标签: node.js express

第一次,它正在做预期的事情。 但是我不知道为什么它会再次召唤自己,即使我全身都有未定义的检查,它仍在打印。

router.post('/:id?', function (req, res) {
    var id = req.params.id;
    console.log(id);
    if (id!== 'undefined') {
        debugger;
    console.log(req.method);  
    console.log('body: ' + JSON.stringify(req.body));
        console.log(req.body.query.toString());
    }

    if(req.body != 'undefined')
        res.render('index', { title: 'Shisodia Mimanshu', query: 'Random Query', text: 'Success 111' + req.body.query });
});

在控制台输出

1

POST
body: {"query":"hahahhahahha"}

hahahhahahha

POST /1 200 55.494 ms - 1015

undefined

POST

body: {}

POST / 500 13.445 ms - 1408

1 个答案:

答案 0 :(得分:0)

此post方法的响应未发送,这是您获得两个输出的原因。一旦响应被发送回客户端,服务器调用就会结束。并且检查ID是否为null应该是来自' undefined',' undefined'是一个字符串。

router.post('/:id?', function (req, res) {
var id = req.params.id;
console.log(id);
if (id!= null) {
    debugger;
console.log(req.method);  
console.log('body: ' + JSON.stringify(req.body));
    console.log(req.body.query.toString());
res.end('Completed')
}

if(req.body != null)
    res.render('index', { title: 'Shisodia Mimanshu', query: 'Random Query', text: 'Success     111' + req.body.query });
res.end('Done')
});

希望这有帮助。

相关问题