Node.js / Firebase:发送标头后无法设置标头

时间:2018-11-10 11:21:33

标签: node.js firebase express

我们有一个express.js / firebase项目,该项目带有/ api / progress POST路由,该路由将标记作为参数,如果扫描的标记等于存储故事顺序的数组中用户的当前进度,则将其递增。为此,我们有一个GET路由/ api / progress返回用户进度。我们检查扫描标记的数量是否等于storyOrder [userProgress](由于数组索引而减一),则用户的进度是从api / progress /?user =“ user”路径获得的。

Number(marker) === storyOrder[response.data.data]-1时,我们在firebase数据库中将进度增加一。但是,运行代码时,有时会产生以下错误:

Error: Can't set headers after they are sent.
at validateHeader (_http_outgoing.js:491:11)
at ServerResponse.setHeader (_http_outgoing.js:498:3)
at ServerResponse.header (/Users/user/Documents/projects/project/node_modules/express/lib/response.js:767:10)
at ServerResponse.send (/Users/user/Documents/projects/project/node_modules/express/lib/response.js:170:12)
at ServerResponse.json (/Users/user/Documents/projects/project/node_modules/express/lib/response.js:267:15)
at userDB.on.data (file:///Users/user/Documents/projects/project/routes/api.mjs:104:15)
at /Users/user/Documents/projects/project/node_modules/@firebase/database/dist/index.node.cjs.js:4465:22
at exceptionGuard (/Users/user/Documents/projects/project/node_modules/@firebase/database/dist/index.node.cjs.js:691:9)
at EventList.raise (/Users/user/Documents/projects/project/node_modules/@firebase/database/dist/index.node.cjs.js:9727:17)
at EventQueue.raiseQueuedEventsMatchingPredicate_ (/Users/user/Documents/projects/project/node_modules/@firebase/database/dist/index.node.cjs.js:9681:41)

这是/ api / progress GET和POST路由的代码:

获取进度:

router.get('/progress', async (req, res, next) => {
let name = req.query.user || null;
console.log('Name: ',name);
let progress;
let dataList;

try {
  const getData = async data => {
    if (data.val()) {
    let tmp = await data.val();
    progress = parseInt(tmp[name].progressCounter);
    console.log(progress);
    // Return progress
    res.json({ status: 200, data: progress });
  } else {
    res.json({ status: 500, err: 'No data! ' });
  }
};

const errData = error => {
  console.error('Something went wrong.');
  console.error(error);
};

dataList = await userDB
  .orderByKey()
  .equalTo(name)
  .on('value', getData, errData);
} catch (err) {
  console.log('Error: ', err.message)
  res.json({ status: 500, err: 'Error while getting progress' });
}

});

POST进度:

router.post('/progress', async (req, res, next) => {
const user = req.session.user;
const marker = req.body.marker;
if (marker!== undefined) {
  const updateProgress = async progress => {
  let updateProg = progress.data;
  updateProg++;
  await userDB.child(user).update({ progressCounter: updateProg });
  res.json({ status: 200, marker: updateProg });
};
axios
  .get(`http://localhost:5000/api/progress?user=${user}`)
  .then(function(response) {
    console.log(storyOrder[response.data.data]-1);
    if (Number(marker) === storyOrder[response.data.data]-1) {
      updateProgress(response.data);
    } else {
      res.status(304);
      res.json({ status: 304 });
    }
  })
  .catch(function(error) {
    console.log(error);
  });
}else{
  res.json({status: 304})
}

});

1 个答案:

答案 0 :(得分:0)

您收到该错误的原因是,您在函数中间调用了res.send()并且代码继续执行

这段代码称为

const getData = async data => {
    if (data.val()) {
    let tmp = await data.val();
    progress = parseInt(tmp[name].progressCounter);
    console.log(progress);
    // Return progress
    res.json({ status: 200, data: progress });
  } else {
    res.json({ status: 500, err: 'No data! ' });
  }

由于发生错误,称为

res.json({ status: 500, err: 'No data! ' });

然后这个

dataList = await userDB
  .orderByKey()
  .equalTo(name)
  .on('value', getData, errData);
} catch (err) {
  console.log('Error: ', err.message)
  res.json({ status: 500, err: 'Error while getting progress' });
}

这将使用新的res.json再次调用第一段代码,但是由于响应已经发送,您会收到该错误