Chandrashekhar Bakker
Chandrashekhar Bakker

Reputation: 13

Ajax Post Request from domain(localhost:9393) to another domain(localhost:9696): Spring Rest

I have a form in one app running in localhost:9393 JS function to post data is:

function registerClient() {
		var postData = $("#client-reg").serializeArray();
		var formURL = "http://localhost:9393/mPaws/client/register?type=eSchool";
		$.ajax({
			url : formURL,
			type : 'POST',
			beforeSend: function (xhr) {
				xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
			},
			data : postData,
			success : function(data, textStatus, jqXHR) {
				console.log(data);
				registrationSuccessPage();
			},
			error : function(jqXHR, textStatus, errorThrown) {
				console.log(textStatus);
				console.log(jqXHR);
				console.log(errorThrown);
			}
		});

	}

And i have post method in spring controller:

@CrossOrigin(origins = "http://localhost:9696")
	@RequestMapping(value = "/client/register", method = RequestMethod.POST)
	@ResponseBody ValidationResponse registerClient(@ModelAttribute("user")User user, BindingResult errors, @Param String type) {
		ValidationResponse response = new ValidationResponse();
		getUserValidator().validate(user, errors);
		if(errors.hasErrors()) {
			response.setStatus("FAIL");
			List<FieldError> allErrors = errors.getFieldErrors();
			List<ErrorMessage> errorMesages = new ArrayList<ErrorMessage>();
			for (FieldError objectError : allErrors) {
				errorMesages.add(new ErrorMessage(objectError.getField(), objectError.getDefaultMessage()));
			}
			response.setErrorMessageList(errorMesages);
		}else {
			Role role = new Role();

			if(type.equalsIgnoreCase("eSchool")) {
				role.setId(3);
				user.setType("eSchool");
			}else if(type.equalsIgnoreCase("ePathLab")) {
				role.setId(1);
				user.setType("ePathLab");
			}else {
				role.setId(0);
			}

			User savedUser = null;
			if(role.getId() > 0) {
				user.setPassword(getUserService().getEncryptedPassword(user.getPassword()));
				user.setEnabled(false);
				user.setRole(role);
				
				savedUser = getUserService().addUser(user);
			}
			if(savedUser != null) {
				boolean mailSent = true;
				if(mailSent){
					response.setStatus("SUCCESS");
				}
			}else {
				response.setStatus("FAIL");
			}
		}
		return response;
	}

On pressing submit i am getting error:

XMLHttpRequest cannot load http://localhost:9393/mPaws/client/register. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9696' is therefore not allowed access. The response had HTTP status code 403.

Please help me with this.

Upvotes: 1

Views: 54

Answers (2)

Chandrashekhar Bakker
Chandrashekhar Bakker

Reputation: 13

The ajax post function:

function registerClient() {
		var postData = $("#client-reg").serializeArray();
		var formURL = "http://localhost:9393/mPaws/client/register?type=eSchool";
		$.ajax({
			url : formURL,
			type : 'POST',
			data : postData,
			headers: {
				"Access-Control-Allow-Origin" : "*"
			},
			success : function(data, textStatus, jqXHR) {
				console.log(data);
				registrationSuccessPage();
			},
			error : function(jqXHR, textStatus, errorThrown) {
				console.log(textStatus);
				console.log(jqXHR);
				console.log(errorThrown);
			}
		});

	}

And the post method in spring controller:

@CrossOrigin(origins = "http://localhost:9696")
	@RequestMapping(value = "/client/register", method = RequestMethod.POST, headers = {"Access-Control-Allow-Origin=*"})
	@ResponseBody ValidationResponse registerClient(@ModelAttribute("user")User user, BindingResult errors, @Param String type) {
		ValidationResponse response = new ValidationResponse();
		getUserValidator().validate(user, errors);
		if(errors.hasErrors()) {
			response.setStatus("FAIL");
			List<FieldError> allErrors = errors.getFieldErrors();
			List<ErrorMessage> errorMesages = new ArrayList<ErrorMessage>();
			for (FieldError objectError : allErrors) {
				errorMesages.add(new ErrorMessage(objectError.getField(), objectError.getDefaultMessage()));
			}
			response.setErrorMessageList(errorMesages);
		}else {
			Role role = new Role();

			if(type.equalsIgnoreCase("eSchool")) {
				role.setId(3);
				user.setType("eSchool");
			}else if(type.equalsIgnoreCase("ePathLab")) {
				role.setId(1);
				user.setType("ePathLab");
			}else {
				role.setId(0);
			}

			User savedUser = null;
			if(role.getId() > 0) {
				user.setPassword(getUserService().getEncryptedPassword(user.getPassword()));
				user.setEnabled(false);
				user.setRole(role);
				
				savedUser = getUserService().addUser(user);
			}
			if(savedUser != null) {
				boolean mailSent = true;
				if(mailSent){
					response.setStatus("SUCCESS");
				}
			}else {
				response.setStatus("FAIL");
			}
		}
		return response;
	}

Working fine.

Upvotes: 0

shi
shi

Reputation: 511

You have to provide cross domain access. You can do this by adding header to your response.

  • Access-Control-Allow-Origin
  • Access-Control-Allow-Methods
  • Access-Control-Max-Age
  • Access-Control-Allow-Headers

    response.addHeader("Access-Control-Allow-Origin", "*");
    
    response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, HEAD");
    response.addHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept");
    response.addHeader("Access-Control-Max-Age", "1728000");
    

Upvotes: 1

Related Questions