简体   繁体   中英

Problem with .json as request response in NodeJS

I am developing a backend with a database in mongoDB, when defining an endpoint of type post and testing it in postman it sends me an error in the console and in postman I do not get the object that I defined as a response to the post, however if it performs the incersion correctly in the database

this is the route

/*
    /api/hospitales
*/
const { Router } = require('express');
const { check } = require('express-validator');
 
const {
    getHospitales,
    crearHospital,
    actualizarHospital,
    eliminarHospital
} = require('../controller/hospitales_controller');
 
const { validarCampos } = require('../middlewares/validarCampos_middleware');
const { validarJWT } = require('../middlewares/validarJWT_middleware');
 
const router = Router();
 
router.get('/', [], getHospitales);
 
router.post('/', [
    validarJWT,
    check('nombre', 'El nombre del hospital es necesario').not().isEmpty(),
    validarCampos
], crearHospital);
 
router.put('/:id', [], actualizarHospital);
 
router.delete('/:id', [], eliminarHospital);
 
module.exports = router;

this is the controller

    const { response } = require('express');
 
const Hospital = require('../model/hospitales_model');
 
const crearHospital = async(req, res = response) => {
 
    const uid = req.uid;
    const hospital = new Hospital({
        usuario: uid,
        ...req.body
    });
 
    try {
 
        const hospitalDB = await hospital.save();
 
        res.json({
            ok: true,
            hospital: hospitalDB
        });
 
    } catch (error) {
        console.log(error);
        res.status(500).json({
            ok: false,
            msg: 'Hable con el administrador'
        });
    }
 
};

This is the model

    const { Schema, model } = require('mongoose');
 
const HospitalSchema = Schema({
 
    nombre: {
        type: String,
        required: true
    },
    img: {
        type: String,
    },
    usuario: {
        required: true,
        type: Schema.Types.ObjectId,
        ref: 'Usuario'
    }
 
}, { collection: 'Hospitales' });
 
HospitalSchema.method('toJSON', function() {
    const { __v, ...object } = this.toObject();
    return object;
});
 
module.exports = model('Hospital', HospitalSchema);

this is the error in console

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:536:11)
    at ServerResponse.header (Z:\NODE\N_BackEndAdminPro\node_modules\express\lib\response.js:771:10)
    at ServerResponse.send (Z:\NODE\N_BackEndAdminPro\node_modules\express\lib\response.js:170:12)
    at ServerResponse.json (Z:\NODE\N_BackEndAdminPro\node_modules\express\lib\response.js:267:15)
    at crearHospital (Z:\NODE\N_BackEndAdminPro\controller\hospitales_controller.js:24:13)
    at processTicksAndRejections (internal/process/task_queues.js:93:5) {
  code: 'ERR_HTTP_HEADERS_SENT'
}
(node:14752) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:536:11)
    at ServerResponse.header (Z:\NODE\N_BackEndAdminPro\node_modules\express\lib\response.js:771:10)
    at ServerResponse.send (Z:\NODE\N_BackEndAdminPro\node_modules\express\lib\response.js:170:12)
    at ServerResponse.json (Z:\NODE\N_BackEndAdminPro\node_modules\express\lib\response.js:267:15)
    at crearHospital (Z:\NODE\N_BackEndAdminPro\controller\hospitales_controller.js:31:32)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:14752) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:14752) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

this is the result in postman

邮递员结果

Solved, Like many of the code problems that exist it was simply an extra call of the next() function in the validateJWT middleware that accompanies the request

bad code

const jwt = require('jsonwebtoken');
const validarJWT = (req, res, next) => {

//leer token
const token = req.header('x-token');

if (!token) {
    return res.status(401).json({
        ok: false,
        msg: 'No hay token en la peticion'
    });
}

try {
    const { uid } = jwt.verify(token, process.env.JWT_SECRET);
    req.uid = uid;
    next();

} catch (error) {
    return res.status(401).json({
        ok: false,
        msg: 'Token invalido'
    });
}

next();
};

rigth code

const jwt = require('jsonwebtoken');
const validarJWT = (req, res, next) => {

//leer token
const token = req.header('x-token');

if (!token) {
    return res.status(401).json({
        ok: false,
        msg: 'No hay token en la peticion'
    });
}

try {
    const { uid } = jwt.verify(token, process.env.JWT_SECRET);
    req.uid = uid;

} catch (error) {
    return res.status(401).json({
        ok: false,
        msg: 'Token invalido'
    });
}

next();
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM