发送后无法设置标题 [英] Cant set headers after they are sent

查看:41
本文介绍了发送后无法设置标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有后端的Express后端,但一切正常,但偶尔会出错

发送后的无法设置标题

服务器掉线.我搜索了可能发生此错误的几种方法,但是在我的代码中我找不到这种情况.我试图在代码中尽可能地简单./p>

Server.js文件

 //调用我们需要的包const addItem = require('./controllers/addItem');const addCategory = require('./controllers/addCategory');const addSubCategory = require('./controllers/addSubCategory');const getSubCategory = require('./controllers/getSubCategoryByCategory');const getCategory = require('./controllers/getAllCategory');const getAllItems = require('./controllers/getAllItems');const cors = require('cors');const express = require('express');//致电快递const app = express();//使用express定义我们的应用const bodyParser = require('body-parser');//将应用程序配置为使用bodyParser()//这将使我们从POST获取数据app.use(bodyParser.urlencoded({Extended:true}));app.use(bodyParser.json());app.use(cors());const port = process.env.PORT ||8080;//设置我们的端口//我们的API的路线//============================================================================const addItemRoute = express.Router();//获取快速路由器的实例const getCategoryRoute = express.Router();const addCategoryRoute = express.Router();const addSubCategoryRoute = express.Router();const getSubCategoryRoute = express.Router();const getAllItemsRoute = express.Router();getCategoryRoute.get('/get_category',(req,res)=> {getCategory(res);});addCategoryRoute.post('/add_category',(req,res)=> {addCategory(req.body.name,res);});getSubCategoryRoute.get('/get_subcategory/:catId',(req,res)=> {getSubCategory(req.params.catId,res);});addSubCategoryRoute.post('/add_subcategory',(req,res)=> {addSubCategory(req.body.name,req.body.cat_id,res);});//代码,名称,数量,长度,描述和子类别ID应该作为参数传递addItemRoute.post('/add_item',(req,res)=> {addItem(req.body.item,res);});getAllItemsRoute.get('/get_items',(req,res)=> {getAllItems(res);});//我们的API的更多路由将在此处//注册我们的路线-------------------------------//我们所有的路线都将以/api作为前缀app.use('/api',addItemRoute);app.use('/api',getCategoryRoute);app.use('/api',addCategoryRoute);app.use('/api',addSubCategoryRoute);app.use('/api',getSubCategoryRoute);app.use('/api',getAllItemsRoute);//启动服务器//============================================================================app.listen(port);console.log(`服务器在端口$ {port}上启动); 

getAllCategories()函数

  Object.defineProperty(exports,'__esModule',{值:true,});const pool = require('./connection');module.exports =函数(res){pool.getConnection((err,connection)=> {如果(错误){connection.release();返回res.json({代码:100,状态:'连接数据库错误'});}console.log(`连接为ID $ {connection.threadId}`);connection.query('select * from category;',(err,rows)=> {connection.release();如果(!err){返回res.json(rows);}});connection.on('error',err => res.json({代码:100,状态:'连接数据库中的错误'})));});}; 

解决方案

如果您在 connection.query()中遇到错误,则会发送带有 res.json()的响应.在您发送另一个响应的 connection.on('error')中捕获了此错误.您不能将两个响应发送到同一请求.似乎在这种情况下,您根本根本不需要 connection.on(),或者如果您要捕获其他错误,请不要在 connection.query上发送响应()的错误.

I am using express backend with a react frontend everything is working fine but occasionally i get error

Cant set header after they are sent

and server gets down.i searched few ways this error might happen but in my code i could not find such cases.i tried to be simple as possible in the code.can anyone please point me what might be the issue?

Server.js file

// call the packages we need
const addItem = require('./controllers/addItem');
const addCategory = require('./controllers/addCategory');
const addSubCategory = require('./controllers/addSubCategory');
const getSubCategory = require('./controllers/getSubCategoryByCategory');
const getCategory = require('./controllers/getAllCategory');
const getAllItems = require('./controllers/getAllItems');
const cors = require('cors');
const express = require('express');
// call express
const app = express(); // define our app using express
const bodyParser = require('body-parser');

// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());

const port = process.env.PORT || 8080; // set our port

// ROUTES FOR OUR API
// =============================================================================
const addItemRoute = express.Router(); // get an instance of the express Router
const getCategoryRoute = express.Router();
const addCategoryRoute = express.Router();
const addSubCategoryRoute = express.Router();
const getSubCategoryRoute = express.Router();
const getAllItemsRoute = express.Router();

getCategoryRoute.get('/get_category', (req, res) => {
  getCategory(res);
});

addCategoryRoute.post('/add_category', (req, res) => {
  addCategory(req.body.name, res);
});

getSubCategoryRoute.get('/get_subcategory/:catId', (req, res) => {
  getSubCategory(req.params.catId, res);
});

addSubCategoryRoute.post('/add_subcategory', (req, res) => {
  addSubCategory(req.body.name, req.body.cat_id, res);
});

// code, name, quantity, length, description and subcategory id should be passed as parameters
addItemRoute.post('/add_item', (req, res) => {
  addItem(req.body.item, res);
});

getAllItemsRoute.get('/get_items', (req, res) => {
  getAllItems(res);
});

// more routes for our API will happen here

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', addItemRoute);
app.use('/api', getCategoryRoute);
app.use('/api', addCategoryRoute);
app.use('/api', addSubCategoryRoute);
app.use('/api', getSubCategoryRoute);
app.use('/api', getAllItemsRoute);

// START THE SERVER
// =============================================================================
app.listen(port);
console.log(`Server started on port ${port}`);

getAllCategories() function

Object.defineProperty(exports, '__esModule', {
  value: true,
});
const pool = require('./connection');

module.exports = function (res) {
  pool.getConnection((err, connection) => {
    if (err) {
      connection.release();
      return res.json({ code: 100, status: 'Error in connection database' });
}

console.log(`connected as id ${connection.threadId}`);

connection.query('select * from category;', (err, rows) => {
  connection.release();
  if (!err) {
    return res.json(rows);
  }
});

    connection.on('error', err => res.json({ code: 100, status: 'Error in connection database' }));
  });
};

解决方案

If you get an error in connection.query() you send a response with res.json(). This error is caught in connection.on('error') where you send another response. You can't send two responses to the same request. It seems that in this case, you don't really need connection.on() at all or if you have it to catch other errors, don't send a response on connection.query()'s error.

这篇关于发送后无法设置标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆