0

我正在尝试使用express Js提供一些文件。我在heroku中部署了这个应用程序,它工作得很好。但是当我尝试使用前端(Angular)从我的应用程序发送请求时,它被 cors 阻塞。这只发生在文件发送路线上。

快递js代码:

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}`));

角度请求代码:

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)
    });
}

来自控制台的屏幕截图: 控制台

4

1 回答 1

0

我的问题是我在 express.static() 中间件之后注入了 cors() 中间件。所以 cors() 没有在我提供文件的路线上运行。当涉及到 nodeJs 中间件时,顺序很重要

于 2021-07-05T08:09:15.840 回答