简体   繁体   中英

Use Node.JS as REST server and web server

I am writing an application with Angular.js and Node.js.

There is a client-side app written in HTML & Angular.js that needs a web server like Apache to be online.

There is also a server-side REST webservice written in Node.js, built on restify (but I don't care which REST API I use, I can use another one).

I can get the whole thing working using a Node.js server for the REST webservice, and another Node.js server for serving the client-side webapp. But I'd like to have only one Node.js server running , on one URL/port (to prevent cross-domain AJAX requests).

How can I do so?

Not sure if this is applicable to your current problem - but app.use() in Express can let one main application set sub-applications to handle different route prefixes. So you could have your main application point any requests starting with /store/ to one Express app, and any requests to /app/ with a second Express app.

http://expressjs.com/api.html#app.use

You can use a proxy before Nodejs. Fastest nginx

Example (nginx):

server {
    listen 80;
    server_name example.com

    # Only http://example.com/api/~
    location /api/ {
        proxy_pass  http://localhost:8000; # node.js app
        proxy_redirect     off;
        proxy_set_header   Host             $host;
        proxy_set_header   X-Real-IP        $remote_addr;
        proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
    }

    location ~* \.(jpg|jpeg|gif|png|css|js|json|woff|zip|tgz|gz|swf|ico|txt|xml)$ {
        expires max;
        root /var/www/site_path;
    }
}

You want to serve both client side app and API from same URL...

(to prevent cross-domain AJAX requests).

Why? This doesn't scale and goes against standard restful API implimentations. Ultimately you are going to want to support CORS because universal adpation will be here as early as next year with the new IE11 and IE12 rollouts. JSONP can be a fallback until they arive.

There is nothing wrong with cross-domain AJAX requests and are recently encouraged --- hence the widespread adoption of this convention.

And if you really need to restrict cross domain API requests, just whitelist the domains you want to grant access too under your node server --- easy as that.

You want to serve both client side app and API from same port...

  1. Proxy pass node server on api.domain.com through NGINX.

  2. Move client-side app to static doc root under NGINX.

Now both are sitting on PORT 80, and only one node server is being used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM