Nginx Nodejs Rest API端点返回404

时间:2019-02-08 08:01:57

标签: node.js reactjs nginx

我正在尝试为本地网络设置本地服务器。 React应用程序运行良好,可以从网络上的另一台计算机进行访问。问题是,我创建的API端点返回404错误(但没有返回Nginx 404)。它被视为常规的Reactjs应用程序内部页面。

这是我的Nginx conf文件:

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    root /var/www/build;

    index index.html index.htm index.nginx-debian.html;

    server_name _;

    # This is the react app
    location / {
            try_files $uri /index.html;
    }

    # This is the restful api
    location /api {
            proxy_redirect       off;
            default_type         application/json;
            proxy_pass_header    Server;
            proxy_set_header     X-Real-IP $remote_addr;
            proxy_set_header     X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header     X-Scheme $scheme;
            proxy_set_header     Content-Type: application/json;
            proxy_set_header     Host $host;
            proxy_set_header     X-NginX-Proxy true;
            proxy_connect_timeout   5;
            proxy_read_timeout      240;
            proxy_intercept_errors  on;
            proxy_pass           http://localhost:5000;
    }
}

这是我的React应用`package.json:

{
    "name": "React APP",
    "version": "0.1.0",
    "private": true,
    "dependencies": {
        ...
    },
    "scripts": {
        ...
    },
    "devDependencies": { 
        ...
    },
    "homepage": "."
}

在我的本地主机上,我能够访问http://localhost/,它向我显示我的ReactApp很好,但是http://localhost/api/v1/及其所有端点均未正确映射。但是,如果我访问http://localhost:5000,我也可以访问我的api。

有人可以告诉我我做错了什么吗?

1 个答案:

答案 0 :(得分:0)

应用程序在不同的端口上运行,React Application为80,NodeJS服务器为5000。在conf.d文件夹下为两个应用程序有两个单独的配置,即下面的react.conf

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    root /var/www/build;

    index index.html index.htm index.nginx-debian.html;

    server_name _;

    # This is the react app
    location / {
            try_files $uri /index.html;
    }
}

,对于NodeJS端点,您可以拥有nodejs.conf

server {
            listen  80 default_server;
            server_name   nodeapi.com;
            # Redirect all HTTP to HTTPS
            location / {
                        proxy_redirect       off;
                        default_type         application/json;
                        proxy_pass_header    Server;
                        proxy_set_header     X-Real-IP $remote_addr;
                        proxy_set_header     X-Forwarded-For $proxy_a dd_x_forwarded_for;
                        proxy_set_header     X-Scheme $scheme;
                        proxy_set_header     Content-Type: application/json;
                        proxy_set_header     Host $host;
                        proxy_set_header     X-NginX-Proxy true;
                        proxy_connect_timeout   5;
                        proxy_read_timeout      240;
                        proxy_intercept_errors  on;
                        proxy_pass         "http://localhost:5000";
               }
        }