如何修复节点中的“已发送标头”错误

时间:2019-04-29 14:55:31

标签: node.js express ldap

因此,我试图创建一个调用ldap服务并验证用户身份的节点应用。在下面的代码中,该应用程序成功连接到服务器并处理了请求。但是当我尝试发送回响应时,出现此错误: 抛出新的ERR_HTTP_HEADERS_SENT('set'); ^

错误[ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后无法设置

我不太确定为什么会这样。我对node,express和ldap很新

// ldapjs required for ldap connection
const ldap = require('ldapjs');

//express required for exposing endpoints
const express = require('express');
const app = express();

const assert = require('assert');

var client = ldap.createClient({
  url: 'ldap://someserve.com'
});

//Search filter for users in the directory
var opts = {
  filter: '(&(objectCategory=person)(objectClass=user))',
  scope: 'sub',
};

//General Ldap serch user
var UserName = '123.test.com';
var Pass = '123longpass'

//Base URL
app.get('/', (req,res) => {
    res.send('hello from node')
});

//Get all ldap users
app.get('/api/ldapUsers', (req, res) => 
{
    client.bind(UserName, Pass, function (err) 
    {
        client.search('DC=sdf,DC=sdfa,DC=gdfgd', opts, function (err, search) 
        {
            search.on('searchEntry', function (entry) 
            {
                res.setHeader('Content-Type', 'application/json');
                var users = entry.object;
                console.log(users);

                res.json(users);
                res.end(); 
            });
        });
    });

   // client.unbind( err => {
   //     assert.ifError(err);
   // });
});

const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}...`));

1 个答案:

答案 0 :(得分:0)

每个发现的项目都会调用一次searchEntry事件,这意味着您多次调用res.json。

尝试一下:

app.get('/api/ldapUsers', (req, res) => 
{
    client.bind(UserName, Pass, function (err) 
    {
        client.search('DC=sdf,DC=sdfa,DC=gdfgd', opts, function (err, search) 
        {
            var users = [];
            search.on('searchEntry', function (entry) {
                users.push(entry.object); 
            });
            search.on('end', function (entry) {
                res.setHeader('Content-Type', 'application/json');
                console.log(users);

                res.json(users);
                res.end(); 
            });
        });
    });
});