Cross-Ori­gin Re­source Shar­ing (CORS): A Primer

OpenSource For You - - Contents -

IFor se­cu­rity rea­sons, browsers re­strict cross-ori­gin HTTP re­quests. If the coder is not aware of this or for­gets about it, it can be pretty frus­trat­ing as the re­quired re­sults will not be ob­tained. Here is an in­stance of such an oc­cur­rence, which the au­thor demon­strates how to solve.

t was a lovely Sun­day af­ter­noon in Ben­galuru. Un­for­tu­nately, I was stuck with my code. I had come up with an idea re­lated to so­cial me­dia, and for the past few weeks, I had been cod­ing to de­velop a so­lu­tion for this idea. Well, this ar­ti­cle 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 ex­plain why I got stuck with the code and how I fi­nally solved the prob­lem.

First, I will need to give read­ers a lit­tle back­ground. There is a pro­file-cre­ation ser­vice that I have writ­ten us­ing Spring Boot, and I have started that ser­vice on Port 8082. I have also writ­ten an An­gu­lar code snip­pet, through which I am con­sum­ing the ser­vice to store pro­file data in Mon­goDB. The An­gu­lar lo­cal server is run­ning on Port 4200. A small piece of the code has been re­pro­duced be­low:

ad­dPro­file ser­vice

im­port com.iWant.repos­i­tory.Pro­file; @RestCon­troller @Re­questMap­ping(value=”/api”) pub­lic class Pro­fileSer­viceCon­troller {

@Au­towired pri­vate Pro­fileSer­vice pro­fileSer­vice; @Re­questMap­ping(method=Re­questMethod.POST,value=”/ ad­dPro­file/pro­file”)

//pub­lic String ad­dPro­file(@PathVari­able String fname) pub­lic Re­spon­seEn­tity<Pro­file> ad­dPro­file(@Re­questBody Pro­file pro­file)

{ try {­fileSer­vice.saveOrUp­date(pro­file);

} catch (Ex­cep­tion e) {

// TODO Auto­gen­er­ated catch block e.print­S­tack­Trace(); } re­turn new Re­spon­seEn­tity<Pro­file>(pro­file, HttpS­ta­tus.OK);

} @Re­questMap­ping(method=Re­questMethod.GET,value=”/ getPro­file”) pub­lic Pro­file find­Name(String fname)

{ re­turn­fileSer­vice.find(fname);

} }

Newspapers in English

Newspapers from India

© PressReader. All rights reserved.