letmejustfixthat letmejustfixthat - 1 year ago 323
Node.js Question

npm start - using CORS

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"

Answer Source

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'); //  <------------------

  port: argv.port || 3000,
  server: {
    baseDir: options.baseDir,
    middleware: [
      cors(), //  <------------------
      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.

Hope it helps you, Thierry

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download