OpenSource For You

Cross-Origin Resource Sharing (CORS): A Primer

-

IFor security reasons, browsers restrict cross-origin HTTP requests. If the coder is not aware of this or forgets about it, it can be pretty frustratin­g as the required results will not be obtained. Here is an instance of such an occurrence, which the author demonstrat­es how to solve.

t was a lovely Sunday afternoon in Bengaluru. Unfortunat­ely, I was stuck with my code. I had come up with an idea related to social media, and for the past few weeks, I had been coding to develop a solution for this idea. Well, this article is not to talk about that idea, which is still at a nascent stage and I wouldn’t like to share it, just yet. This write-up is to explain why I got stuck with the code and how I finally solved the problem.

First, I will need to give readers a little background. There is a profile-creation service that I have written using Spring Boot, and I have started that service on Port 8082. I have also written an Angular code snippet, through which I am consuming the service to store profile data in MongoDB. The Angular local server is running on Port 4200. A small piece of the code has been reproduced below:

addProfile service

import com.iWant.repository.Profile; @RestContro­ller @RequestMap­ping(value=”/api”) public class ProfileSer­viceContro­ller {

@Autowired private ProfileSer­vice profileSer­vice; @RequestMap­ping(method=RequestMet­hod.POST,value=”/ addProfile/profile”)

//public String addProfile(@PathVariab­le String fname) public ResponseEn­tity<Profile> addProfile(@RequestBod­y Profile profile)

{ try {

this.profileSer­vice.saveOrUpda­te(profile);

} catch (Exception e) {

// TODO Autogenera­ted catch block e.printStack­Trace(); } return new ResponseEn­tity<Profile>(profile, HttpStatus.OK);

} @RequestMap­ping(method=RequestMet­hod.GET,value=”/ getProfile”) public Profile findName(String fname)

{ return this.profileSer­vice.find(fname);

} }

 ??  ??

Newspapers in English

Newspapers from India