Patrickkx
Patrickkx

Reputation: 1870

Nodejs - API and application on the same server issue

I have a server, which holds my API and my application.

/ - returns my application

/api - every request starts with that pre word api, e.g. /api/users and so on.

My issue: When I enter my app not by directly example.com, but e.g. example.com/users or even some random word, like example.com/stackOverflow it returns API response!! My app does not even start, the response is like Cannot GET /stackOverflow

I guess it's because it's on one, single server... Is there a way to fix it somehow in node?

var app = expres();

app.get("/api/users", function (req, res) {
    getUsers(function (err, users) {
        if (err) {
            return res.status(500).send('Error');
        }

        return res.json(users);
    });
});

app.get("/api/user/:_id", function (req, res) {
    getUserById(req.params._id, function (err, user) {
        if (err) {
            return res.status(500).send('Error');
        }

        return res.json(user);
    });
});

Upvotes: 0

Views: 188

Answers (1)

Murilo
Murilo

Reputation: 649

You could create different subdomains instead of using the same domain just changing URI.

Then with reverse proxy configuration on nginx/apache you could redirect the requests to different server ports. That way you could have your application running on port 80 and your NodeJS API on port 3000 let's say.

Example:

APP.domain.com redirects to localhost:80

API.domain.com redirects to localhost:3000

I hope I made myself clear.

You could also do that with the structure you already have not needing to run them on different ports. Here is some documentation regarding how to configure that on nginx:

https://docs.nginx.com/nginx/admin-guide/web-server/reverse-proxy/

Upvotes: 1

Related Questions