我应该打开服务器的3000端口来服务NodeJS应用程序吗?

时间:2020-07-18 08:56:37

标签: node.js angular express deployment server

我有一个Angular + Node.JS应用程序。当我在本地运行程序时,我在Angular应用程序中定义了一个baseurl = http://localhost:3000/,并使用该前缀访问程序定义链接中的NodeJS后端,但是现在,当我想在远程服务器上部署应用程序时,将baseurl的定义更改为baseurl = http://111.222.333.444:3000/(例如111.222.333.444是我的服务器ip地址),但是它不起作用!

我应该如何将Angular应用程序连接到远程服务器上的NodeServer?

编辑:这是我的/etc/nginx/nginx.conf文件内容:

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  _;
        root         /demo/stock-front9/dist/strategy;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
            #proxy_pass http://localhost:3000;
            #proxy_http_version 1.1;
            # First attempt to serve request as file, then

            # as directory, then redirect to index(angular) if no file found.
            try_files $uri $uri/ /index.html;
        }

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }

2 个答案:

答案 0 :(得分:1)

我不会,我认为最好使用PM2之类的工具运行Node应用,然后在其前面使用Nginx放置反向代理,PM2将充当服务的协调器,而Nginx将提供只能通过标准Web端口(80、443)访问。

对于Angular,在编译时,它会生成一个静态Web应用程序,您可以使用相同的Nginx反向代理来提供服务,这样做就像这样,您将省去了配置诸如CORS,API路由之类的工作等等,一切都会通过Nginx。

更新Nginx配置文件示例

server {
  listen 80;
  server_name example.org;

  location /api {
      proxy_pass http://localhost:3000;
      proxy_set_header Host            $host;
      proxy_set_header X-Forwarded-For $remote_addr;
      proxy_redirect off;
      proxy_http_version      1.1;
  }
  
  location / {
      root /path/to/angular/compiled/app;
      index index.html;
  }
 
}

然后,角度应用程序应指向同一主机。

祝你好运:)

答案 1 :(得分:0)

您仍然可以在本地运行角度应用程序。对于后端服务器,您可以使用代理。 请看看这个。 https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md#using-corporate-proxy