简体   繁体   English

res.send不能正常工作

[英]res.send not working properly

I am working with a simple CRUD app with jquery ajax and node.js, just to improve my skills with node and ajax. 我正在使用一个简单的CRUD应用程序与jquery ajax和node.js,只是为了提高我的节点和ajax技能。 The thing is that I am doing a post request that is handled with my post router in the node server, and everything is working fine. 问题是我正在做一个使用我在节点服务器中的post路由器处理的post请求,一切正常。 It adds 1 more product to my products.json file, but in the end it doesn't send the response back to the client, the final res.send("done") doesn't work and I don't know why.. 它在我的products.json文件中增加了1个产品,但最终它没有将响应发送回客户端,最终res.send(“done”)不起作用,我不知道为什么。 。

here is the code: 这是代码:

ajax 阿贾克斯

$("#create-form").on('submit',function(){
    event.preventDefault();
    var createIn = $("#create-input").val();
    $.ajax({
        url: '/products',
        method:'POST',
        data:JSON.stringify({name:createIn}),
        contentType: "application/json",
        dataType: "json",
        success: function(data){
          console.log(data);
          $("create-input").val("");
          $("get-button").click(); 
        }
    });
})

node 节点

app.post('/products',function(req,res){
    fs.readFile('products.json','utf8',function(err,data){
        var result = JSON.parse(data);
        var productName = req.body.name;
        console.log(req.body.name);
        currentId++;
        var productId = currentId;
        var product = {
            name: productName,
            id: productId
        }
        result.products.push(product);
        fs.writeFile(__dirname + "/products.json",JSON.stringify(result),'utf8');
     });
    res.send("post done");
});

This is just the important part of the code, it works and just fails at the end in the res.send. 这只是代码的重要部分,它可以正常工作,并且最终在res.send中失败了。

This does not answer your question directly but you should ideally not send back the response until you know the work has been done, and you should handle errors. 这不能直接回答您的问题,但理想情况下,在您知道工作已完成之前,您应该不回复响应,并且您应该处理错误。 In other words you should use the callbacks. 换句话说,您应该使用回调。 (Too many callbacks can be problematic and you should investigate other patterns - eg promises - bit no need here) (太多的回调可能会有问题,您应该调查其他模式 - 例如承诺 - 这里不需要)

app.post('/products',function(req,res){
    fs.readFile('products.json','utf8',function(err,data){
        if (err) return res.send("error");
        var result = JSON.parse(data);
        var productName = req.body.name;
        console.log(req.body.name);
        currentId++;
        var productId = currentId;
        var product = {
            name: productName,
            id: productId
        }
        result.products.push(product);
        fs.writeFile(__dirname + "/products.json",JSON.stringify(result),'utf8', function(err, res) {
         if (err) return res.send("error");
         res.send("post done");
        });
     });

});

Your client code is looking for a json response, but you are returning a string. 您的客户端代码正在寻找json响应,但您返回一个字符串。

$("#create-form").on('submit',function(){
    event.preventDefault();
    var createIn = $("#create-input").val();
    $.ajax({
        url: '/products',
        method:'POST',
        data:JSON.stringify({name:createIn}),
        contentType: "application/json",
        dataType: "json",           <--------------
        success: function(data){
          console.log(data);
          $("create-input").val("");
          $("get-button").click(); 
        }
    });
})

Either delete this line or add on the server side 删除此行或在服务器端添加

res.send({"message":"post done"});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM