【问题标题】:How can I solve this error in nano (couchdb) Express.js如何解决 nano (couchdb) Express.js 中的此错误
【发布时间】:2018-09-06 20:02:25
【问题描述】:

(节点:7636)UnhandledPromiseRejectionWarning:错误:发送后无法设置标头。
在 validateHeader (_http_outgoing.js:491:11)
在 ServerResponse.setHeader (_http_outgoing.js:498:3)
在 ServerResponse.header (C:\Users\username\path\Express\node_modules\express\lib\response.js:767:10)
在 ServerResponse.send (C:\Users\username\path\Express\node_modules\express\lib\response.js:170:12)
在 ServerResponse.json (C:\Users\username\path\Express\node_modules\express\lib\response.js:267:15)
在 ServerResponse.send (C:\Users\username\path\Express\node_modules\express\lib\response.js:158:21)
在 body.rows.forEach (C:\Users\username\path\Express\app.js:41:15)
在 Array.forEach ()
在 db.list.then (C:\Users\username\path\Express\app.js:40:19)

(节点:7636)UnhandledPromiseRejectionWarning:未处理的承诺拒绝。此错误源于在没有 catch 块的情况下抛出异步函数内部,或拒绝未使用 .catch() 处理的承诺。 (拒绝编号:2)

查询代码如下:

app.get("/api/customers", (req, res, next) =>{
    res.header("Access-Control-Allow-Origin", "http://localhost");
    res.header("Access-Control-Allow-Methods", "GET, POST");
    res.writeHead(200, {'Content-Type': 'application/json'});
    
    db.list({ include_docs: true }).then((body) => {
        body.rows.forEach((doc) => {
          res.send(doc.doc);
        });
      });
  });

我想使用 angularjs 在 html 页面上显示数据。

任何帮助我都会非常感激。

【问题讨论】:

    标签: angularjs express nano


    【解决方案1】:

    您试图在循环内多次发送数据,因此出现该错误。 你为什么不像下面这样发送全身数据:

    app.get("/api/customers", (req, res, next) =>{
    
        db.list({ include_docs: true }).then((body) => {
            res.send({data: body.rows});
        }).catch(e => {res.status(500).send({msg: 'Sorry, something went wrong'})});
      });
    

    更新 1

    要启用 CORS,请创建一个中间件并将其添加到您的应用中

    //CORS middleware
    var allowCrossDomain = function(req, res, next) {
        res.header('Access-Control-Allow-Origin', '*');
        res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
        res.header('Access-Control-Allow-Headers', 'Content-Type');
    
        next();
    }
    
    app.use(allowCrossDomain)
    

    【讨论】:

    • 用您的答案更新代码后,我在控制台日志中收到此消息 Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at localhost:800/api/customers. (原因:CORS 请求未成功)。
    • 我已经在我的 express REST 文件夹中安装了 cors,但我仍然收到错误消息
    • 您能否分享一下您如何启用 CORS 的服务器端代码?
    猜你喜欢
    • 1970-01-01
    • 2017-10-06
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 2017-12-12
    • 2012-02-14
    • 2015-04-12
    • 2016-06-21
    相关资源
    最近更新 更多