2

I am running a backend Laravel API and a frontend Vue.js application.

Option #1 would be to set those two up as follows:

api.example.com => serving the API
app.example.com => serving the frontend appplication

However this gets you in all the trouble with CORS, OPTIONS preflight etc.

So in order to avoid that, I am planning on setting it up like this:

app.example.com/api => serving the API
app.example.com => serving the frontend appplication

So no more CORS problems, but since I am using Webpack I am running into issues in local development. Webpack dev server is serving the frontend at:

app.example.com:8080

So again, I am running into CORS when trying to access the API on port 80 :-(

Help! How can I set this up, so I don't have to deal with CORS yet being able to make use of the Webpack dev server and the Laravel (Homestead) API backend?

I assume it's not possible to serve both Homestead as well as Webpack from the same hostname and port. But is there any set-up that avoids CORS?

santacruz
  • 1,236
  • 2
  • 12
  • 24

2 Answers2

4

There is a way to avoid doing cors requests by using the proxy mechanism. Then you basically have the solution you described with app.example.com/api for the backend and app.example.com for the frontend. The webpack-dev-server takes your requests and forwards them to the configured backend. An exemplary configuration could look like that:

devServer: {
    proxy: {
        '/api*': {
            target: 'http://app.example.com:8080'
        },
    },
},

Depending on how your backend is set up, you possibly need to have a look at the rewrite function to do some processing of the path before handing the request to the backend.

For more details, please see the webpack-dev-server docs at: https://webpack.github.io/docs/webpack-dev-server.html#proxy

If you want to run this stuff in production, then you will not use the webpack-dev-server but either set up the proxy configuration in the web server you are using (e.g. apache or nginx).

Andreas Jägle
  • 11,632
  • 3
  • 31
  • 31
  • thanks! this works perfectly... I also just found some more info here: https://vuejs-templates.github.io/webpack/proxy.html – santacruz Oct 25 '16 at 15:37
  • by the way... thanks for also pointing out the server side requirements! makes your answer very complete and helpful! – santacruz Oct 26 '16 at 07:26
0

Related answer: CORS error on same domain?

Domain, subdomain and port needs to be the same, which basically means unless you are serving both the app and api from the same server, you need to take care of CORS. There is no escape from that.

Your webpack development environment can help you with your vue.js app only. It cannot do the server side of things. You will need your server on a different port. So you will have to set Access-Control-Allow-Origin:* for all your API requests.

Official reference: https://www.w3.org/Security/wiki/Same_Origin_Policy

Community
  • 1
  • 1
Mani
  • 23,635
  • 6
  • 67
  • 54