spectacularbob spectacularbob - 2 months ago 17
Apache Configuration Question

Angular2 Test Data Without CORS

I am writing a project with an Angular2 frontend and a REST WebAPI backend using php.

I have been running/debugging the frontend using

npm's
lite server (aka
npm start
). Until now, I have been using the
in-memory-web-api
to serve data, but I am ready to start consuming real data from the backend.

In production, both frontend and backend would be served from the same Apache server, but in development I have been using
npm
to run Angular2 and a separate Apache server to run the API.

My problem is that
npm
runs on
localhost:3000
and Apache on
localhost:80
. This creates cross origin security issues and the only way I can have my Angular2 app get data is to enable CORS on my REST API. I don't want to enable CORS on the backend if I can avoid it because I am worried that it may somehow make it's way into production.

So far,
npm's
server has been really nice because it compiles my .ts files automatically and will refresh the browser whenever it detects a change to the files. I would really rather not have to move my Angular2 development into Apache unless there is a way to keep these nice features.

Is there any way to keep these two things separate without having to enable CORS?

If not, is there a way I can merge the two while keeping npm's nice features?

Answer

Configure your development application server to proxy requests to the development REST server. Then make same origin requests.

Alternatively, use .htaccess to turn CORS headers on but add it to .gitignore (or your version control system's equivalent) to ensure it stays out of production.

Alternatively, if your REST server has a configuration system. Use that to turn on CORS in development (and again, ensure that the config file is kept out of version control).

Comments