0

I am trying to serve some files using express Js . i deployed this application in heroku , it work just fine .but when trying to send requests from my application with frontend (Angular) it blocks by cors . and this happen only with file sending route .

Express js code :

const express = require('express');
var cors = require('cors')
const app = express();
const PORT = process.env.PORT || 8080;

app.use(express.static('public'));
app.use(cors());

app.use(function(req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
});

app.get('/', (req, res) => {
    res.send('Hello World!');
});
app.get('/test', (req, res) => {
    res.json({ username: 'Flavio' })

});
app.get('/:path_file', function(req, res){
    console.log(req.params.path_file);
    res.sendFile('public/'+req.params.path_file,{ root: __dirname });
  }); 

app.listen(PORT, () => console.log(`Server listening on port: ${PORT}`));

Angular requests code :

export class AppComponent {


  constructor(private processVisualisationService: ProcessVisualisationService,public http: HttpClient){
    const optionRequete = {
      headers: new HttpHeaders({
        'Access-Control-Allow-Origin':'*'
      })
    };
    this.http.get('https://safe-brook-89233.herokuapp.com/test',optionRequete).subscribe(data => {
      console.log(data)
    });
    this.http.get('https://safe-brook-89233.herokuapp.com/c4_diagram.bpmn.txt',optionRequete).subscribe(data => {
      console.log(data)
    });
}

Screenshots from console : console

  • Does this answer your queation: https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe – Drashti Dobariya Jul 03 '21 at 14:28

1 Answers1

0

My problem was that i injected cors() middleware after express.static() middleware . so the cors() didn't run on the route where i serve files . Order is important when it comes to nodeJs Middlewares