JavaScript Request POST

1
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery.post demo</title>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script></head><body><formaction="/" id="searchForm">
  <input type="text" name="s" placeholder="Search...">
  <input type="submit" value="Search">
</form>
<!-- the result of the search will be rendered inside this div -->
<div id="result"></div>

<script>

$( "#searchForm" ).submit(function( event ) {

  // Stop form from submitting normally
  event.preventDefault();

  // Get some values from elements on the page:
  var $form = $( this ),
    term = $form.find( "input[name='s']" ).val(),
    url = $form.attr( "http://192.168.1.140:8080/vectis/account/vialaser/webservice/cliente/consultarCliente" );

  // Send the data using post
  var posting = $.post( "http://192.168.1.140:8080/vectis/account/vialaser/webservice/cliente/consultarCliente", { cpfCliente: term } );

  // Put the results in a div
  posting.done(function( data ) {

    alert('Passou');
  });
});
</script>

</body>
</html>

I have this code, but look what it returns:

  

XMLHttpRequest can not load    link .   In 'Access-Control-Allow-Origin' header is present on the requested   resource. Origin 'null' is therefore not allowed access. The response   had HTTP status code 422.

He does not enter the alert at all.

Documentation: link

With ajax:

<script>
jQuery(document).ready(function() { 
  jQuery('#conversion-form').submit(function(){             
    event.preventDefault();

  $.ajax({
    type: 'POST',
    url: "http://localhost:8080/vectis/account/vialaser/webservice/cliente/consultarCliente",

    data: 'cpfCliente=078.736.879-29',
    contentType: "application/x-www-form-urlencoded",
    crossDomain : true,
    dataType: 'application/json',
    success: function(data) { alert("Success"); },
    error: function(data) { alert('Failed!'); },

});
  return false;
 });
});
</script>
<form class="form-horizontal" id="conversion-form">
  <div class="form-group" style="margin-top: 15px;">
    <label class="col-md-4 control-label" for="email">E-mail</label>  
    <div class="col-md-4">
      <input id="cpfCliente" name="cpfCliente" type="text" class="form-control input-md" required="true">
    </div>
  </div>
  <div class="form-group">
    <label class="col-md-4 control-label" for="botaoenviar"></label>
    <div class="col-md-4">
      <button id="botaoenviar" name="botaoenviar" class="btn btn-success">Enviar</button>
    </div>
  </div>
</form>
    
asked by anonymous 15.12.2016 / 18:06

1 answer

1

The alert is triggered because the POST request completed successfully and the server response was 422, ie there was a response from the server although code 422 represented an error.

The error "XMLHttpRequest can not load." is a response from the browser to the server response, which returned code 422, so the function that is passed as a parameter to the done method will be executed.

For security reasons, browsers restrict cross-source HTTP requests initiated from scripts. So, since your web app uses XMLHttpRequest , you could only make HTTP requests for your own domain.

Your source domain is not the same as the request domain, however cross-source resource sharing (CORS) is possible.

See the stream below:

Considerthegreenrectanglethedomainofyourapplication(localhost)andthepinkrectanglethedomain(192.168.1.140)oftheHTTPrequest.

ThestreamistriggeredbyanXHRcallmadebyJavaScript,therequestwillbeexecutednormallyif:

  • UseGET,HEADorPOSTmethods;
  • IsaGETrequestwithoutcustomheaders;
  • IsaHEADrequestwithoutcustomheaders;
  • ThisisaPOSTrequestwiththeheaderContent-typedefault(application/x-www-form-urlencoded,multipart/form-dataortext/plain)withoutcustomheaders.

Incontrasttosimplerequests(discussedabove),preflightedrequestsfirstsendanHTTPrequestbytheOPTIONSmethodtotheresourceintheotherdomaintodetermineiftheactualrequestissecuretobesent,serverhastheopportunitytodetermineifyouwanttoacceptarequestunderthesecircumstances.

TheserverinturnrespondswiththeAccess-Control-*headers,forexample:

//indicaçãodequeodominio"example.com" tem permissões para aceder ao recurso
Access-Control-Allow-Origin: http://example.com

// indicação de quais métodos serão permitidos na requisição real
Access-Control-Allow-Methods: POST, GET, OPTIONS

// indicação de quais cabeçalhos serão permitidos na requisição real
Access-Control-Allow-Headers: Content-Type

// indicação de que quanto tempo os resultados de uma solicitação "preflight" podem ser amazenados em cache
Access-Control-Max-Age: 3600

Here you can see everything on this subject. The above information can be verified using, for example, the Google Chrome console on the "Network" tab.

Based on the information above, the problem will only be solved when the request is considered safe by the server where the resource is located (which in its case is the server 192.168.1.140), ie it is necessary to change the response header from the server.

I can not help this part because I do not know which language is used, whether or not a framework has been implanted, etc. However, the solution is to accept an HTTP request using the OPTIONS method and return the headers we saw above. / p>     

15.12.2016 / 21:23