vendredi 27 mars 2015

Posting to MongoDB using Spring Data REST via AJAX



Newbie to working with Spring and Java so bare with me... I've been working with Spring's tutorial on creating and retrieving objects stored in a MongoDB using Spring Data REST.

I would like to be able to post to the Spring REST with Ajax, but I know I can't currently because of no cross-domain support. Whats the best way to get around this for my purpose and keeping this blueprint of what I'd like to accomplish Obviously I can post via cURL cmd, but I'd like to implement a JS function. Thanks for any insight.


I have my Repository here:



package com.hello;

import java.util.List;

import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource(collectionResourceRel = "people", path = "people")
public interface PersonRepository extends MongoRepository<Person, String> {

List<Person> findByLastName(@Param("name") String name);

}


Person Class here:



package com.hello;


import org.springframework.data.annotation.Id;

public class Person {

@Id private String id;

private String firstName;
private String lastName;

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}
}


JS



$('#clickme').click(function(){
var formData = {firstName:"John",lastName:"doe"};

$.ajax({
url : "http://localhost:8080/people",
type: 'POST',
dataType: 'json',
data: formData,
contentType: 'application/json',
processData: false,
success: function (data) {
console.log(data);
},
error: function(){
console.log("Cannot get data");
}
});

});



Aucun commentaire:

Enregistrer un commentaire