npm start - using CORS

2019-04-28 23:14发布

问题:

I'm working on a little app, using Angular2. In the 5min. Quickstart Guide npm is used to install required modules and to start a lite-server. Later I want to use that app within a normal web-server and build mobile apps with cordova. How ever, I'm using a REST api to load some data. How can I configure the lite-server to solve CORS pre-flight OPTIONS check? My apache server (on a dedicated server) is already configured, but I don't want to commit, update and recompile every little change. I need a corresponding configuration to this:

Header always set Access-Control-Allow-Origin "https://my-domain.net:12345"
Header always set Access-Control-Allow-Headers "X-Requested-With, Content-Type, Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Max-Age "1000"

回答1:

There is no built-in option to do that within the lite-server. That said, you can patch it but I don't really see what you try to do here...

After having installed it, you can go into the node_modules/lite-server folder and install the connect-cors module:

npm install connect-cors

Then in the lib/lite-server.js file, you can import the module and use it the middleware array after:

var historyFallback = require('connect-history-api-fallback');
var log = require('connect-logger');
var cors = require('connect-cors'); //  <------------------
(...)

sync.init({
  port: argv.port || 3000,
  server: {
    baseDir: options.baseDir,
    middleware: [
      cors(), //  <------------------
      log(),
      historyFallback({ index: options.fallback })
    ]
  },
  files: options.files,
});

When starting the server with the following command the CORS support is usable:

./bin/lite-server --baseDir ../../

By adding an Origin header in requests, you will see CORS headers in the response.



回答2:

actually the lite-server is just a wrapper of browser-sync, if you can check the documents from https://www.browsersync.io/docs/options, you can find the configuration of cors, and because lite-server support use a config file to set the options, so all you need to do is just set a config file for lite-server, you can select bs-config.js or bs-config.json, if we use the easiest one bs-config.json, the contente is:

{
    "cors": true
}

then you directly start lite-server, you can see:

browser-sync config

{ injectChanges: false,
  files: [ './**/*.{html,htm,css,js}' ],
  watchOptions: { ignored: 'node_modules' },
  server: { baseDir: './', middleware: [ [Function], [Function] ] },
  cors: true }

[BS] Access URLs:

   Local: http://localhost:3000

that means cors works.



回答3:

I found with http-server

http-server -o --cors