gpt4 book ai didi

node.js - Node JS 和 Sequelize 错误 : Cannot set headers after they are sent to the client

转载 作者:行者123 更新时间:2023-12-03 22:22:56 25 4
gpt4 key购买 nike

当我尝试执行查询以将用户名从 id 获取到 Controller 时出现此错误。我试图解决这个问题,但没有解决办法,有没有办法通过查询获取用户名?
用户模型:

'use strict';
const {
Model
} = require('sequelize');
const config = require('../config');
module.exports = (sequelize, DataTypes) => {
class tb_user extends Model {

static associate(models) {
}
};
tb_user.init({
id_user:{
type:DataTypes.INTEGER,
primaryKey:true,
autoIncrement:true
},
username: DataTypes.STRING,
email: DataTypes.STRING,
password: DataTypes.STRING
}, {
sequelize,
modelName: 'tb_user',
freezeTableName:true
});

tb_user.associate = models =>{
tb_user.hasMany(models.tb_tech,{
foreignKey:'id_user',
as:'tb_tech',
onDelete:'CASCADE'
})
}
return tb_user;
};
主管模型:
'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class tb_supervisor extends Model {

static associate(models) {
}
};
tb_supervisor.init({
id_supervisor:{
type:DataTypes.INTEGER,
primaryKey:true,
autoIncrement:true
},
username: DataTypes.STRING,
email: DataTypes.STRING,
password: DataTypes.STRING
}, {
sequelize,
modelName: 'tb_supervisor',
freezeTableName:true
});

tb_supervisor.associate = models =>{
tb_supervisor.hasMany(models.tb_tech,{
foreignKey:'id_supervisor',
as:'tb_tech',
onDelete:'CASCADE'
})
}
return tb_supervisor;
};
技术员模型:
'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class tb_tech extends Model {
static associate(models) {
}
};
tb_tech.init({
id_tech:{
type:DataTypes.INTEGER,
primaryKey:true,
autoIncrement:true
},
id_user: DataTypes.INTEGER,
id_supervisor: DataTypes.INTEGER,
zone:DataTypes.INTEGER,
region:DataTypes.INTEGER,
full_name: DataTypes.STRING,
tech_type: DataTypes.STRING,
goal: DataTypes.FLOAT,
observations: DataTypes.STRING,
client: DataTypes.STRING
}, {
sequelize,
modelName: 'tb_tech',
freezeTableName:true
});

tb_tech.associate = models =>{
tb_tech.belongsTo(models.tb_user,{
foreignKey:'id_user',
as:'tb_user',
onDelete:'CASCADE'
})

tb_tech.belongsTo(models.tb_supervisor,{
foreignKey:'id_supervisor',
as:'tb_supervisor',
onDelete:'CASCADE'
})
}

return tb_tech;
};
主管 Controller :
const Supervisor = require("../models").tb_supervisor;
const Tecnico = require("../models").tb_tech;
const Usuario = require("../models").tb_user;

module.exports = {
getAllSupervisors(req,res){
const id_supervisor = req.params.id_supervisor;
return Supervisor
.findAll({
include:[{
model:Tecnico, as:'tb_tech',
where:{
id_supervisor:id_supervisor
}
}]
})
.then(sup => {
const resObj = sup.map(supervisor => {
return Object.assign(
{},
{
id_supervisor : supervisor.id_supervisor,
username: supervisor.username,
email: supervisor.email,
technician: supervisor.tb_tech.map(tec => {
return Object.assign(
{},
{
tech_id : tec.id_tech,
id_user: Usuario.findOne({
where:{
id_user:tec.id_user
},
attributes:['username']
}).then(user => res.json(user)).catch(error => console.log(error)),
id_supervisor: tec.id_supervisor,
zone: tec.zone,
region: tec.region,
full_name: tec.full_name,
tech_type:tec.tech_type,
goal: tec.goal,
observations: tec.observations,
client: tec.client
}
)
})
}
)
})
res.status(200).json(resObj);
})
.catch(error => {
res.status(500).send({message:error.message});
})
},
}
路线:
const router = require('express').Router();
const UsuarioController = require("../controllers/user");
const TecnicoController = require("../controllers/tech");
const SupervisorController = require("../controllers/supervisor");

router.use(function(req,res,next){
res.header(
"Access-Control-Allow-Headers",
"x-access-token, Origin, Content-Type, Accept",
"Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE",
"Access-Control-Allow-Origin", "*"
);
next();
});

router.get('/users/getAllUsers/:id_user',UsuarioController.getAllUsers);

router.get('/supervisor/getAllSupervisors/:id_supervisor',SupervisorController.getAllSupervisors);

router.get('/techs/getAllTechs',TecnicoController.getAllTechs);

module.exports = router;
在 postman 中,查询很好,但我需要用户名的字段是一个空白对象,控制台抛出以下错误。可以在另一个查询中进行查询吗?
图片:
enter image description here
enter image description here
问题是,错误的根源是什么?您可以在另一个查询中进行查询吗?
事先非常感谢。

最佳答案

顾名思义,这是因为您尝试多次发送响应 header ,即在第一和第二位这是不可能的,请尝试根据 nodejs 的异步行为更改您的代码使用 async await 避免函数链接避免使 async调用 map、filter 和数组的其他异步函数,因为它们不会等待 foruse native 或 for of loop

module.exports = {
getAllSupervisors(req, res) {
const id_supervisor = req.params.id_supervisor;
return Supervisor.findAll({
include: [
{
model: Tecnico,
as: "tb_tech",
where: {
id_supervisor: id_supervisor
}
}
]
})
.then((sup) => {
const resObj = sup.map((supervisor) => {
return Object.assign(
{},
{
id_supervisor: supervisor.id_supervisor,
username: supervisor.username,
email: supervisor.email,
technician: supervisor.tb_tech.map((tec) => {
return Object.assign(
{},
{
tech_id: tec.id_tech,
id_user: Usuario.findOne({
where: {
id_user: tec.id_user
},
attributes: ["username"]
})
.then((user) => res.json(user)) // sending response here for first time
.catch((error) => console.log(error)),
id_supervisor: tec.id_supervisor,
zone: tec.zone,
region: tec.region,
full_name: tec.full_name,
tech_type: tec.tech_type,
goal: tec.goal,
observations: tec.observations,
client: tec.client
}
);
})
}
);
});
res.status(200).json(resObj); //for second time
})
.catch((error) => {
res.status(500).send({ message: error.message });
});
}
};
为了避免这种尝试做这样的事情
module.exports = {
async getAllSupervisors(req, res) {
const id_supervisor = req.params.id_supervisor;
const sub = await Supervisor.findAll({
include: [
{
model: Tecnico,
as: "tb_tech",
where: {
id_supervisor: id_supervisor
}
}
]
});
// const resObj = sup.map((supervisor) => {
const resObj = [];
for (const supervisor of sub) {
resObj.push(
Object.assign(
{},
{
id_supervisor: supervisor.id_supervisor,
username: supervisor.username,
email: supervisor.email,
technician: supervisor.tb_tech.map((tec) => {
return Object.assign(
{},
{
tech_id: tec.id_tech,
id_user: await Usuario.findOne({
where: {
id_user: tec.id_user
},
attributes: ["username"]
}),
id_supervisor: tec.id_supervisor,
zone: tec.zone,
region: tec.region,
full_name: tec.full_name,
tech_type: tec.tech_type,
goal: tec.goal,
observations: tec.observations,
client: tec.client
}
);
})
}
)
);
}
// });
res.status(200).json(resObj); //second
res.status(500).send({ message: error.message });
}
};

关于node.js - Node JS 和 Sequelize 错误 : Cannot set headers after they are sent to the client,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67798872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com