【问题标题】:angular application run using node is being blocked by CORS使用节点运行的角度应用程序被 CORS 阻止
【发布时间】:2021-10-16 16:24:40
【问题描述】:

我正在尝试将 Angular 应用程序部署到 Heroku,为此我必须创建一个 sever.js 文件,以便可以使用 node.js 完成部署。 问题是从我的应用程序到我的 api 应用程序的任何请求(也使用 heroku 中的容器注册表部署)被 cors 阻止。

server.js:

function requireHTTPS(req, res, next) {
    // The 'x-forwarded-proto' check is for Heroku
    
    next();
}
const allowedOrigins = ['my-api'];

const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors({
    credentials: true,
    origin: (origin, callback) => {
      if (!origin || allowedOrigins.includes(origin)) {
          console.log(origin);
          callback(null, true) ;
      } else {
        callback(new Error(`Origin: ${origin} is now allowed`))
      }
    }
  }));
app.use(requireHTTPS);
app.use(express.static('./dist/HygeneSpa'));
app.get('/*', function(req, res) {
    res.sendFile('index.html', {root: 'dist/HygeneSpa/'}
  );
});
app.listen(process.env.PORT || 8080);

错误:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at api-app. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

我注意到的另一件事是 OPTIONS 请求不包含 cors 标头,但 POST 请求包含。

【问题讨论】:

    标签: node.js angular heroku


    【解决方案1】:

    在下面使用它会像专业人士一样工作。

    //Install express server
    const express = require('express');
    const path = require('path');
    const compression = require('compression')
    const app = express();
    app.use(compression())
    
    // Serve only the static files form the dist directory
    // Replace the '/dist/<to_your_project_name>'
    app.use(express.static(__dirname + '/dist/{appname}'));
    
    app.get('*', function (req, res) {
        // Replace the '/dist/<to_your_project_name>/index.html'
        res.sendFile(path.join(__dirname + '/dist/{appname}/index.html'));
    });
    // Start the app by listening on the default Heroku port
    app.listen(process.env.PORT || 8080);
    

    【讨论】:

    • 这与问题无关:/。我已经在我的文件中这样做了,唯一的问题是 cors。应用程序运行成功!但问题在于 api 调用,它们都被 cors 阻止了。
    • 然后使用 proxy-conf.json 并重新服务应用程序。 stackoverflow.com/questions/37172928/…
    • 当我使用 ng serve 为应用程序提供服务时,一切正常,但是当我使用 node server.js 运行我的服务器时,我被 cors 阻止了
    • 知道了。你有没有用邮递员测试你的节点api为8080端口。
    • API 由托管服务器 (.net api) 提供服务,我使用节点服务器只是为了运行 Angular 应用程序。 '对于我请了几天假的迟到的答案,我真的很抱歉'
    猜你喜欢
    • 2020-05-01
    • 2022-01-24
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    • 2019-07-24
    • 2013-06-06
    • 2021-12-05
    • 2022-06-12
    相关资源
    最近更新 更多