如何使用NGINX和NodeJS配置客户端-服务器Web应用程序

时间:2019-03-02 18:39:37

标签: node.js amazon-web-services nginx web-applications cors

我有一个客户端-服务器应用程序,其中NGINX和NodeJ部署在Amazon AWS EC2实例上。

部署了客户端和服务器,然后设置了NGINX配置文件以监听客户端的URL和端口。

当我运行客户端时,它可以运行,但是每次尝试调用服务器API时,都会出现连接错误。

这是配置文件:

server {
listen 80;
server_name default_server;
location / {
    proxy_pass http://127.0.0.1:3000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
    proxy_redirect off;
 if ($request_method = 'OPTIONS') {
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    #
    # Custom headers and headers various browsers *should* be OK with but aren't
    #
    add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
    #
    # Tell client that this pre-flight info is valid for 20 days
    #
    add_header 'Access-Control-Max-Age' 1728000;
    add_header 'Content-Type' 'text/plain; charset=utf-8';
    add_header 'Content-Length' 0;
    return 204;
 }
 if ($request_method = 'POST') {
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
    add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
 }
 if ($request_method = 'GET') {
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
    add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
 }

环顾四周,我还添加了一些配置以启用CORS请求,猜测这可能是我的问题。但是不管有没有它都行不通。

我的疑问是NGINX是否仅需要侦听客户端URL。我还应该为服务器URL添加一个位置吗? (也是本地主机,但在其他端口上)

如果没有,我还能做错什么?

编辑:

我发布了我在Firefox上看到的错误: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at [url].

在Chrome上: Failed to load [url] resource: net::ERR_CONNECTION_REFUSED

0 个答案:

没有答案