使用Node.JS作为REST服务器和Web服务器

Mat*_*oli 9 javascript webserver web-services node.js angularjs

我正在用Angular.js和Node.js编写一个应用程序.

有一个用HTML和Angular.js编写的客户端应用程序需要像Apache这样的Web服务器才能在线.

还有一个用Node.js编写的服务器端REST Web服务,构建于restify(但我不关心我使用哪个REST API,我可以使用另一个).

我可以使用Node.js服务器为REST Web服务工作,而另一个Node.js服务器用于服务客户端webapp.但我想在一个URL /端口上运行一个Node.js服务器(以防止跨域AJAX请求).

我怎么能这样做?

Pla*_*ato 8

不确定这是否适用于您当前的问题 - 但app.use()在Express中可以让一个主应用程序设置子应用程序来处理不同的路由前缀.因此,您可以让您的主应用程序指向从/store/一个Express应用程序开始的任何请求,/app/以及使用第二个Express应用程序的任何请求.

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


小智 5

您可以在Nodejs之前使用代理.最快的nginx

示例(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;
    }
}
Run Code Online (Sandbox Code Playgroud)