I have a web application that I have been working on, which has an AngularJS 1.6 UI with a Spring Boot Java backend. I develop the AngularJS with Visual Studio Code, which is probably the only Microsoft product I have ever used that I feel was really well done, and it works great for AngularJS. I run the code with npm start
on port 8000 by default. The backend is a Spring Boot REST application configured to run on a different port 8181. When, I try to get the frontend to talk to the backend, I get the following issue:
[code language=”bash” wraplines=”true”]
Failed to load http://localhost:8181/restaurants/wingspecials/: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:8000’ is therefore not allowed access.
[/code]
This is because browsers, by default, block cross domain communication due to security concern. If you want to achieve cross domain communication, then you need to do something to allow for it to happen. This is called Cross-Origin Resource Sharing or CORS. There are a few ways to satisfy CORS, such as by using JSON-P (ie, JSON with Padding). However, in my opinion there is a better way when using Spring. With Spring, we can use a special annotation to allow for CORS. Here is an example:
[code language=”java” highlight=”5″]
@RestController
public class WingSpecialController {
@RequestMapping("restaurants/wingspecials")
@CrossOrigin(origins = { "http://localhost:8000" })
public List<WingSpecial> getWingSpecials() {
// do something…
}
}
[/code]
Here we specify in the backend code for a specific REST endpoint to allow for Cross-Origin communication from http://localhost:8000, which is the port the npm
is running the AngularJS code on.
Also, I find that I need to allow for CORS in my actual deployment. Even though both my frontend and backend code is hosted on the same server, I host the frontend on my actual domain (http://www.wingspecials.today) and the backend on a subdomain (http://service.wingspecials.today). This requires CORS as well and order to achieve this you can supply an array to the annotation like so:
[code language=”java” highlight=”5″]
@RestController
public class WingSpecialController {
@RequestMapping("restaurants/wingspecials")
@CrossOrigin(origins = { "http://localhost:8000", "http://www.wingspecials.today" })
public List<WingSpecial> getWingSpecials() {
// do something…
}
}
[/code]
Definitely believe that which you said. Your favorite justification seemed to be at the net the easiest thing to keep in mind of. I say to you, I certainly get irked whilst other folks consider issues that they plainly don’t realize about. You managed to hit the nail upon the highest and defined out the whole thing with no need side effect , other people could take a signal. Will likely be again to get more. Thank you
Very interesting information!Perfect just what I was searching for!