Bridging the communication

As we mentioned, we will need to set up an HTTP proxy on the frontend side to solve the cross-origin request restriction. webpack-dev-server supports HTTP Proxy through the http-proxy-middleware library (https://github.com/chimurai/http-proxy-middleware). To bridge the requests, all we need to do is to change devServer.proxy in front-end/vue.config.js. Before we make the change, we need to come up with a proxy strategy. That is, the requests we will need to use the proxy and how to match those requests.

In general, there are two types of requests in a web application: the page requests and the API requests. The response of a page request is used for rendering a page, while the response of an API request is consumed by JavaScript to fulfill an operation. For example, when you open a login page, the request is a page request. And, when you click the Login button to send the credentials for the backend for authentication, that request is an API request. And, during development, since webpack-dev-server will serve the pages for the frontend, we won't need to proxy page requests. The API requests are those that we need to bridge because it is our backend that will handle those API requests.

Therefore, we need a way to separate the page requests and API requests. One common approach is to use a specific pattern in the URIs of the API requests. In our case, we will make all of the API requests paths start with /api/. In this way, we can use http-proxy-middleware context-matching ability to identify these API requests.

Here is the change we make to the front-end/vue.config.js file:

module.exports = {
devServer: {
...
proxy: {
'/api/*': {
target: 'http://localhost:8080'
}
},
...
}

With this configuration, all the API requests will be bridged to the backend. http-proxy-middleware also supports other ways of matching URIs, which you can find in the guide on its repository on GitHub.

How can we verify if this works or not? A very simple way is to type a URI that doesn't exist, such as http://localhost:3000/api/hello, and the response should be a Whitelabel Error Page that is served by Spring Boot. You will need to start both the backend and the frontend to test this.

Now, let's make the commit and push to origin:

Figure 8.11: Bridging the communication commit
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.120.57