node.jsexpress

Express js cors error for public folder access from other domain


Here is my code

    const app = express();

const limiter = rateLimit({
  windowMs: 1 * 60 * 1000, // 15 minutes
    limit: 60, // Limit each IP to 100 requests per `window` (here, per 15 minutes).
});

app.use(limiter);
app.use(hpp());
app.use(helmet());
app.use(cors())
app.use((req, res, next) => {
  // res.setHeader('Content-Security-Policy', "default-src 'self'; img-src 'self' http://localhost:5000;");
  res.setHeader('Content-Security-Policy', "default-src *; img-src *;");
  next();
});
app.use(express.static(path.join(__dirname, 'public')));

I can access image from same origin. but from different origin it gives cors error


Solution

  • Helmet is blocking public image

    helmet({
          crossOriginResourcePolicy: false,
        })
    

    Adding this will resolve the issue