javascript - 为什么settimeout会破坏Expressjs

标签 javascript node.js express

我在 express.js 中有以下代码

// POST api/posts/:id
exports.post = function(req, res){

    req.body[0].id = posts.length + 1;
    posts.push(req.body[0]);
    console.log(posts);
    fs.writeFileSync("json/posts.json", JSON.stringify(posts));
    setTimeout(function(){
        res.set.apply(res, utils.contentType);
        res.json(req.body[0]);
    }, utils.randomNumberBetween(1000, 3000));


};

当我发布一个简单的 json 对象时,我收到以下错误。

org.apache.http.NoHttpResponseException: localhost:9000 failed to respond

如果我删除 settimeout,一切都会按预期进行。我在其他地方使用过 settimeout,如下所示:

// GET api/posts
exports.get = function(req, res){
    setTimeout(function(){
        res.set.apply(res, utils.contentType);
        res.json(posts);
    }, utils.randomNumberBetween(1000, 3000));
};

所以我不明白为什么它会在发布时中断。有什么想法吗??

最佳答案

这是因为发出请求的应用程序希望在一定时间内(比如 5 秒)收到 express 的响应。如果它没有收到任何回复,它就会认为出了什么问题。要解决此问题,您可以做的一件事是更改“发送/请求”应用程序等待/监听响应的时间。

关于javascript - 为什么settimeout会破坏Expressjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39908813/

相关文章:

javascript - 如何使用后端 Node.js Express-Session 对 React 前端进行身份验证?

javascript - Node.js 导出调用 Controller 中的另一个 Controller 方法

javascript - 附加到 url 的查询导致页面向下跳转

javascript - node.js process.stdout.write 类型错误

javascript - 调整 ES2015 Map 以支持所需的行为

node.js - 类型错误 : Cannot read property '0' of undefined passport-facebook

javascript - 服务器返回空响应

mysql - Nodejs-Express-Mysql : render view after post

javascript - Node.js AWS S3 上传从不调用 End 函数

javascript - 节点.js : Unexpected token {