【问题标题】:Issue running Node Express server and Angular App on NGINX the same server在 NGINX 同一台服务器上运行 Node Express 服务器和 Angular 应用程序的问题
【发布时间】:2020-04-02 01:20:12
【问题描述】:

我正在将我的第一个 Angular 应用程序部署到生产环境中,但我无法让我的 NGINX 服务器访问我在 Express 上的端点。

我的设置(都在同一个 EC2 实例上运行):

  1. node express 服务器成功运行在端口:3000 用于 API(我可以通过浏览器访问端点)

  2. NGINX 服务器通过端口成功托管我的 Angular 应用程序:81。

在我的 Angular 应用程序中,我使用了一个 environment.prod.ts 文件来声明 http 请求的 serverUrl。

export const environment = {
  production: true,
  serverUrl: 'localhost:3000'
};

这是我相当确定我的问题所在的地方。我的服务器 URL 应该是什么?

这是我尝试通过应用程序创建 http req 时遇到的特定错误: error

编辑: 我修复了我的环境文件以包含“http://”,但现在我收到此错误。老实说,我不是 100% 确定 CORS 是如何工作的。我对这一切都很陌生。

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3000/openapp/2019-12-01. (Reason: CORS request did not succeed).

【问题讨论】:

    标签: angular express nginx amazon-ec2


    【解决方案1】:

    您可能缺少 Cors 配置。 这是我在生产环境中工作的=>

    import cors from 'cors';
    const options: cors.CorsOptions = corsOptions: {
      allowedHeaders: ['Origin', 'X-Requested-With', 'Content-Type', 'Accept', 'X-Access-Token'],
      credentials: 'true',
      methods: ['GET', 'HEAD', 'OPTIONS', 'PUT', 'PATCH', 'POST', 'DELETE'],
      origin: '*',
      preflightContinue: true,
      optionsSuccessStatus: 204
    },
    

    在选项请求中将它们用于您的路由器:

    router.options('*', cors(options))
    

    请注意原点“*”。如果您不想让您的 api 通过 ajax 向整个网络开放,请确保将您的域名放在那里。

    还有一件事,如果我可以建议的话,你不必暴露你的 3000 端口,只需通过端口 80 上的 nginx,这样你就可以将你的 api baseUrl 列为 /api 就是这样。

    这就是我个人的做法 => 对于 nginx 部分,这里是 Express 配置:

    upstream node_upstream {
            server      127.0.0.1:3000;
            keepalive   64;
    }
    
    ...
    server {
        location /api {
            ...
    
            client_max_body_size        3M;
            client_body_buffer_size     1M;
            proxy_set_header        X-Real-IP $remote_addr;
            proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header        Host $host;
            proxy_set_header        X-NginX-Proxy true;
            proxy_http_version      1.1;
            proxy_set_header        Upgrade $http_upgrade;
            proxy_set_header        Connection "upgrade";
            proxy_max_temp_file_size    0;
            proxy_pass              http://node_upstream;
            proxy_cache_bypass      $http_upgrade;
            proxy_connect_timeout   120;
            proxy_read_timeout      120;
            proxy_send_timeout      120;
            proxy_redirect          off;
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2021-04-13
      • 2018-12-04
      • 1970-01-01
      • 2019-10-29
      • 2017-11-04
      • 1970-01-01
      • 1970-01-01
      • 2018-12-12
      • 1970-01-01
      相关资源
      最近更新 更多