Confusion about web-application ports

2019-02-28 01:24发布

问题:

I have a project that is already deep in development, and there is a problem with the ports.

The Client is SPA written in backbone, that uses Sails as a server.

Problem is in the fact that Client is running in Express on port 80, while Sails is run on 1337.

I would like to host this backbone application within the Sails, not ouside the sails. A bit more details: When I fire the Fiddler, I am seeing requests being made to localhost:1337/get/user. I need it to reside on port 80 as well.

Backbone is written using standard. I have app.js and main.js with all of the common folders (JS, LIBS, CSS). In other words, I have index.html that has data-main using require.js...

I have not problems running the client in separate node.js... how to run it within Sails.js?

Where do I put my index.html???

回答1:

Trying to serve index.html as a static file won't work. Instead, try the following:

1. Serve your index.html from Sails

Just serve index.html as a combination of views/layout.ejs and views/home/index.ejs, which are mounted to the root / for default newly created Sails project.

2. Set up a catch-all route

In config/routes.js put something like this:

module.exports.routes = {
  '/': {
    view: 'home/index'
  },

  '/:unknownRoute': {
    view: 'home/index'
  }
}

This way you'll be able, for example, to use simple one-level pushstate routing within your SPA: routes like /products or /news will still give you your index.html (if you are using something more complex though, you may want to play a little bit more with your Sails routes).

3. Serve your API with a prefix

In your config/controllers.js put, for example:

module.exports.controllers = {
  ...

  prefix: '/api',

  ...
}

This will let you serve your API with a prefix and have both /api/products (JSON API) and /products (your SPA) routes available.

4. Use any port you want

You can change the default port via config/local.js, even to 80 (if you don't have anything else running on 80, of course).

In production though, it would probably be a better idea to just proxy to default Sails' or any other port with Nginx, for example.