title: Express serving static file: can't set headers after they are send
body: <p>I am using the express.static built-in middleware function to serve static files, but the console prints the error: <strong>Can't set headers after they are sent</strong>.</p>
  
  <p>here is my code, i don't know what is wrong with this</p>
  
  <pre><code>'use strict';
  
  let path = require('path');
  let express = require('express');
  let bodyParser = require('body-parser');
  let mongoose = require('mongoose');
  let formidable = require('express-formidable');
  let routes = require('./routes');
  let app = express();
  let port = process.env.PORT || 3000;
  
  
  let db = mongoose.connect('mongodb://localhost:27017/old-driver');
  
  // deal with img post
  app.use(formidable({
    uploadDir: path.join(__dirname, 'upload'),
    keepExtensions: true
  }));
  
  app.use(bodyParser.urlencoded({extended: true })); 
  app.use(bodyParser.json());
  
  // access-control
  app.all('*', (req, res, next) =&gt; {
    res.set("Access-Control-Allow-Origin", "*");
    res.set("Access-Control-Allow-Headers", "Content-Type,X-Requested-With");
    res.set("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.set("X-Powered-By",' 3.2.1')
    res.type("application/json");
    res.type("jpg");
    next();
  });
  
  
  // set assets path, GET /assets/demo.png
  app.use('/assets', express.static('upload'));
  
  routes(app);
  
  app.listen(port);
  </code></pre>
  
  <p>the route middleware method:</p>
  
  <pre><code>getAllTeachers: (req, res) =&gt; {
      Teacher.find({}, (err, teacher) =&gt; {
          if (err) {
              res.send(err);
          } else {
              res.json(teacher);
          }
      });
  },
  </code></pre>
  
  <p>Even if I remove the access-contol code as shown below, still get error</p>
  
  <pre><code>let db = mongoose.connect('mongodb://localhost:27017/old-driver');
  
  // deal with img post
  app.use(formidable({
    uploadDir: path.join(__dirname, 'upload'),
    keepExtensions: true
  }));
  
  app.use(bodyParser.urlencoded({extended: true })); 
  app.use(bodyParser.json());
  
  // set assets path, GET /assets/demo.png
  app.use('/assets', express.static('upload'));
  
  routes(app);
  
  app.listen(port);
  </code></pre>
  
  <p>when I request 2 existing jpg file, I also get 404 error in one jpg file
  <a href="https://i.stack.imgur.com/7e93Z.png" rel="nofollow noreferrer">404 screenshot</a></p>