3

Update - 2016-01-30

As advised in the comments I have:

  1. installed XAMPP
  2. put my page on Apache and ran the server
  3. made sure the page and the scripts are executing (simple alert test)
  4. set the xhrFields: withCredentials to false to make CORS request as advised in the only answer and taught here

I still cannot pass the request. This is the console log:

XMLHttpRequest cannot load http://localhost:8080/RimmaNew/rest/appointments. 
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 400

Here how it looks on the 'user end' if this is of any help: enter image description here

------------------Initial ticket-----------------------------

I have a java rest application that runs locally and accepts so far one get method and returns a json string: Successful get by id call

Another method is POST, which is supposed to convert, validate and save the information from the sent form and return a 200 answer. If anything goes wrong during conversion, validation or persistence - an exception is thrown (e.g. BadRequest or 500).

This is the rest method (I omitted for brevity validating, build methods as well as the converter and converter provider classes):

@POST
@Produces("application/json")
@Consumes("application/x-www-form-urlencoded")
public Response bookAppointment(@FormParam("date") Date appDate,
        @FormParam("time") Time appTime, @FormParam("type") String appType,
        @FormParam("clientName") String clientName, @FormParam("email") String clientEmail,
        @DefaultValue("") @FormParam("message") String clientMsg) {
    //externalize the validation of all fields to concentrate on "positive"
    //scenario only
    validator(appDate, appTime, appType, clientName, clientEmail);
    Appointment appointment = build(appDate, appTime, appType,clientName, 
                clientEmail, clientMsg);
    try {
        repository.add(appointment);
        return Response.ok(appointment).build();
    } catch (Exception e) {
        throw new InternalServerErrorException("Something happened in the application "
                + "and this apointment could not get saved. Please contact us "
                + "to inform us of this issue.");
    }
}

The client is not within the application (I thought may be this will be useful) - it is a simple HTML file on my computer that has this jQuery script:

<script type='text/javascript'>
    $(document).ready(function(){
         $('form#appointmentForm').submit(function(ev){
             ev.preventDefault();
            $.ajax({
                url: 'localhost:8080/RimmaNew/rest/appointments',
                type: 'post',
                dataType: 'json',
                data: $('form#appointmentForm').serialize(),
                contentType: 'application/x-www-form-urlencoded',
                beforeSend: function() {                        
                    $('#ajaxResponse').html("<img src='245.gif' />");                        
                },
                success: function(data) {
                    $('#ajaxResponse').html("<span style='color:white; background-color: green;' class='glyphicon glyphicon-ok'></span><p>"+JSON.stringify(data)+"</p>")
                    .fadeIn("slow");
                },
                error:  function(xhr, ajaxOptions, thrownError){
                    $('#ajaxResponse').html("<span style='color:white; background-color: red;' class='glyphicon glyphicon-exclamation-sign'></span><p>Status: ").append(xhr.status)
                    .append("</p>").fadeIn("slow");
                }
            });               
        });            
    });
</script>

I want to submit a form in order to access its params with the @FormParam annotated attributes. On every request that I send I do not receive any of the thrown errors and the status is always 0. Do you see where am I erring or what am I missing?

enter image description here

vasigorc
  • 882
  • 11
  • 22
  • What do you mean by *"...client is not within the application - it is a simple HTML file on my computer that has this jQuery script"*, ajax fails due to same-origin if you're running that script from a `file://` protocol. – adeneo Jan 28 '16 at 00:51
  • It is a html file not deployed to any app server. This file simply resides in /home/myusername/subdir1/subdir2/RimmaNew/ Are you saying I can not use jQuery like this? Is there a work-around? – vasigorc Jan 28 '16 at 00:55
  • You can use jQuery, but if this .html file isn't served from an actual webserver with a `http` protocol, you're breaking the same-origin policy, and can't do ajax, as protocols, ports and domains must match. – adeneo Jan 28 '16 at 01:04
  • Thank you. To be honest I never knew of Same-origin policy - have just read-up on wiki about it now. This post seems to have a work-around for this: http://stackoverflow.com/questions/3076414/ways-to-circumvent-the-same-origin-policy – vasigorc Jan 28 '16 at 01:09
  • There are workarounds, most of them won't work with a `file://` protocol, in your case you should just fire up a WAMP server or something similar instead, and you're good. – adeneo Jan 28 '16 at 01:11
  • I have no idea what is WAMP...I have used XAMPP few years ago for a few university PHP projects...But even if I do that wouldn't it still break the same-origin policy? i.e.: same protocol, host and port? Could you please paste a link to a tutorial? Worse come worse I could replace FormParam with QueryParam and fall back to Postman add-on to do my functional test. – vasigorc Jan 28 '16 at 01:20
  • WAMP, XAMPP, EasyPHP ... same same, you need a webserver, and you need to be on the same domain and port. If you can't do that, you have to set some CORS headers, but you still generally won't be able to do ajax from the file protocol. – adeneo Jan 28 '16 at 01:29

1 Answers1

0

A status code of 0 means that the request didn't happen. In order to have a status code a valid http interaction has to happen, if none did there is no status code.

The main reasons why this would happen are:

  1. The DNS could not be resolved
  2. A connection to the host/port could not be established
  3. CORS Issues, the HTML is not being served by the same host/port than the server. In this case you need to write a CORS policy to allow specific domains to make ajax request to the server.
  4. The HTML is a local file, this is a special case of the CORS problem where some browser don't allow connections without a host.

All of them should show an error on the javascript console ( the weirdest would be CORS that shows itself as a failed OPTIONS request )

Mon Villalon
  • 682
  • 3
  • 11