简体   繁体   中英

Error: cannot set headers after they are sent to client

I wrote a simple express app that let user search for a game's name as well as filter according to game's genre and sort by title or ranking. The game data is an array of objects with keys App, Rating, and Genres, etc However I am getting the console error 'Cannot set headers after being sent to client'.

The request still returns the correct filtered results.

What does it mean?

const express = require('express');
const morgan = require('morgan');
const cors = require('cors');
const googleApps = require('./google-apps')

const app = express();
app.use(morgan('common'));
app.use(cors());

app.get('/apps', (req, res) => {

  let {
    search = '', sort, genres
  } = req.query;
  if (sort) {

    if (!['rating', 'app'].includes(sort)) {
      return res.status('400')
        .send('Sort must be one of "app" or "rating"')
    }

  }
  if (genres) {
    if (!['Action', 'Puzzle', 'Strategy', 'Casual', 'Arcade', 'Card'].includes(genres)) {
      return res.status('400')
        .send('Genres must be one of Action, Puzzle, Strategy, Casual, Arcade, Card')
    }

  }

  let results = googleApps.filter(app =>
    app.App
    .toLowerCase()
    .includes(search.toLowerCase())
  )
  if (sort) {

    if (sort === 'rating') {
      sort = 'Rating'
    } else {
      sort = 'App'
    }
    results
      .sort((a, b) => {
        return a[sort] > b[sort] ? 1 : a[sort] < b[sort] ? -1 : 0;
      });
  }
  if (genres) {
    let genreResult = results.filter(app =>
      app
      .Genres
      .toLowerCase()
      .includes(genres.toLowerCase())
    )
    res.json(genreResult)
    console.log(genreResult)


  }
  res.json(results)

})

module.exports = app;

This happens when you try sending more than one response back to the client, which would never work, one request, one response, for example

res.send({ data: "I want to send this message" });
res.send({ data: "But I also want to send this message" });

This would never work, because you're attempting to send multiple responses for the same request.

That happened in your code where you tried to send res.json(genreResult) as @ayush-gupta said, you should return reaching that point where you've sent your response.

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