简体   繁体   中英

415 (Unsupported Media Type) with jquery

I am new to using a RESTful API and I don't know why it is showing this error. I am posting the values through jQuery. Do I need to do something else? This is my jQuery code:

Updated : Now it is showing 405 (Method Not Allowed)

 $(document).ready(function(){ 


$("#patsubmit").click(function() {
    var firstName = $("#firstName").val();
    var lastName = $("#lastName").val();
    var mobileNumber = $("#mobileNumber").val();
    var emailId = $("#emailId").val();

   var dataString = '{"firstName":"'+ firstName + '","lastName":"' + lastName + '","mobileNumber":"' + mobileNumber + '", "emailId":"' + emailId+'"}';
   console.log(dataString); 
   if(firstName=='' )
    {
alert("nothing in it");
    }
    else
    {
    $.ajax({
    type: 'POST',
     url : '/geniedoc/api/patient/register',
     data: dataString,
     contentType: 'application/json',
     dataType: 'json',
     headers: {'Content-Type':'application/json'}
    success: function(){ // Uncaught SyntaxError: Unexpected identifier
console.log();
   }
});}
    return false;
    });

});

This is my Java API. MAIN_PATIENT = api/patient and RestURIConstants.REGISTER = register

@RestController
@RequestMapping(value = RestURIConstants.MAIN_PATIENT)
public class PatientRestController extends AbstractController implements RestURIConstants, GenieDocConstants{

    private static final Logger logger = Logger.getLogger(UserRestController.class);

    @RequestMapping(value = RestURIConstants.REGISTER, method = RequestMethod.POST, consumes ="application/json")
    public @ResponseBody ModelMap registerPatient(HttpServletRequest  request, @RequestBody PatientVo patientVo){
        logger.info("registerPatient : Start");
        long startTime = System.currentTimeMillis();
        ModelMap map = new ModelMap();
        PatientVo patVo;
        try {
            if(patientVo.getFirstName() == null) {
                map.addAttribute(STATUS_CODE, FAILURE);
                map.addAttribute(STATUS_MESSAGE, this.env.getProperty(MESSAGE_FIRST_NOT_EMPTY));
            } else if(patientVo.getEmailId() == null) {
                map.addAttribute(STATUS_CODE, FAILURE);
                map.addAttribute(STATUS_MESSAGE, this.env.getProperty(MESSAGE_EMAIL_NOT_EMPTY));
            } else if(patientVo.getEmailId() == "") {
                map.addAttribute(STATUS_CODE, FAILURE);
                map.addAttribute(STATUS_MESSAGE, this.env.getProperty(MESSAGE_EMAIL_NOT_EMPTY));
            } else if (patientVo.getMobileNumber() == null) {
                map.addAttribute(STATUS_CODE, FAILURE);
                map.addAttribute(STATUS_MESSAGE, this.env.getProperty(MESSAGE_MOBILE_NOT_EMPTY));
            } else {
                patVo = this.patientManagementService.provisionPatient(patientVo);
                if (patVo != null) {
                    map.addAttribute("patientId", patVo.getEmailId());
                    map.addAttribute(STATUS_CODE, SUCCESS_STATUS_CODE_REGPATIENT);
                    map.addAttribute(STATUS_MESSAGE, this.env.getProperty(SUCCESS_STATUS_CODE_REGPATIENT));

                } else {
                    map.addAttribute(STATUS_CODE, ERROR_STATUS_CODE_REG);
                    map.addAttribute(STATUS_MESSAGE, this.env.getProperty(ERROR_STATUS_CODE_REG));
                }
            }
        } catch (MongoDBDocumentNotFoundException e) {
            map.addAttribute(STATUS_CODE, ERROR_STATUS_CODE_REGPATIENT);
            map.addAttribute(STATUS_MESSAGE,this.env.getProperty(ERROR_STATUS_CODE_REGPATIENT));
            logger.error("Error : " + e.getMessage());
            //e.printStackTrace();
        } catch (UserAreadyExsistException e) {
            map.addAttribute(STATUS_CODE, ERROR_STATUS_CODE_REGPATIENT);
            map.addAttribute(STATUS_MESSAGE, this.env.getProperty(ERROR_STATUS_CODE_REGPATIENT));
            logger.error("Error : " + e.getMessage());
            //e.printStackTrace();
        }
        logger.debug("Exit: Total Time Taken: "+ (System.currentTimeMillis() - startTime));
        return map;
    }

You need to set the Content-Type Header to application/json

$.ajax({
    type: 'POST',
    url: '/geniedoc/api/patient/register',
    data: dataString,
    headers: {
        'Content-Type':'application/json'
    }
   .....
}

In your spring controller you are defining, that only content of MIME Type application/json is accepted. Because standard content type text/plain the Spring controller does not accept your request and send back a status code 415 (Media type not supported)

Edit: As user6409738 mentioned, you need to send your data in json format. Otherwise the Spring Controller will cause an exception parsing the body.

For example the solution posted by Yagnesh Agola

var dataString = '{"firstName":"'+ firstName + '","lastName":"' + lastName + '","mobileNumber":"' + mobileNumber + '","emailId":' + emailId+'"}'; 

It depends what your PatientVo Class is looking like

Data you have send to server from client is not in JSON format.

var dataString = 'firstName='+ firstName + '&lastName=' + lastName + '&mobileNumber=' + mobileNumber + '&emailId=' + emailId;   

Above line is used to send data string to server which is not in JSON format it is simple query string.

Either you can convert above string in JSON format

var dataString = '{"firstName":"'+ firstName + '","lastName":"' + lastName + '","mobileNumber":"' + mobileNumber + '","emailId":"' + emailId+'"}'; 

OR

You can directly submit form data in JSON using below code.

var formData = JSON.stringify($("#myForm").serializeArray());
  1. add contentType parameter when use jQuery Ajax
 $.ajax({ type : "POST", contentType : 'application/json', url : "/geniedoc/api/patient/register", data : JSON.stringify({"param1" : "param1", "param2":2}) }) 
  1. remove consumer = "application/json" in your request-mapping definition, (it's not necessary, SpringMVC will auto detect right converter)

because U use @RequestBody in springMVC controller, then SpringMVC will convert the argument with RequestResponseBodyMethodProcessor which use default converters to resolve the argument. default converters list is:

public RequestMappingHandlerAdapter() {
        StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
        stringHttpMessageConverter.setWriteAcceptCharset(false);  // see SPR-7316

        this.messageConverters = new ArrayList<HttpMessageConverter<?>>(4);
        this.messageConverters.add(new ByteArrayHttpMessageConverter());
        this.messageConverters.add(stringHttpMessageConverter);
        this.messageConverters.add(new SourceHttpMessageConverter<Source>());
        this.messageConverters.add(new AllEncompassingFormHttpMessageConverter());
    }

For your situation, MappingJackson2HttpMessageConverter is expect to be used to resolve the argument. And here is the definition of MappingJackson2HttpMessageConverter, it need MediaType of application/json

public MappingJackson2HttpMessageConverter(ObjectMapper objectMapper) {
    super(objectMapper, MediaType.APPLICATION_JSON_UTF8,
            new MediaType("application", "*+json", DEFAULT_CHARSET));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM