Javascript POST Request

Asked

Viewed 3,471 times

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>

<form action="/" 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 cannot load http://192.168. 1.140:8080/vectis/Account/vialaser/webservice/client/consultarCliente. No '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’s not on the alert at all.

Documentation: http://api.jquery.com/jQuery.post/

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>
  • 2
  • Didn’t help.....

  • What seems like this error is that the link you are trying to make the request has controlled access, and you are not allowed to access...

  • But I put a breakpoint on my app and it comes...

  • Look if this link can help you... esta ingles http://stackoverflow.com/questions/20035101/no-access-control-allow-origin-header-is-present-on-the-requested-resource

  • but I think it’s still the same as when Lucas was there...

  • This plugin will probably save you: https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi

  • Poís is, but my customers will not be able to install the plugin, right?

  • CORS always needs to be authorized by the server, not the client. If the service you are consuming does not allow, by normal means you will not be able to do anything. There is how to add the plugin in chome or use a proxy, but it is neither assertive nor practical.

  • I edited the implementation question with ajax, the same happens.

  • So I suggested as duplicate, it is a very common problem and it already has many discussions.

  • @Alisson, $.post and $.ajax are basically the same thing - both are ajax requests.

  • @Alisson, when debugging on the localhost Cors is barred regardless of how the back is configured, when it is in production Cors will only be blocked if the back does not give permission, so no, your clients will not have to install, only Voce to debug on the localhost

  • Now does not return any of Xmlhttprequest cannot load, but still enters the error alert

Show 9 more comments

1 answer

1

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

The error "Xmlhttprequest cannot load." is a browser response to the server’s response, which returned the 422 code, thus the function that is passed as parameter to the method done will be executed.

For security reasons, browsers restrict cross-origin HTTP requests initiated from scripts. So, how your web application uses XMLHttpRequest, 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 is possible (CORS).

See the flow below: inserir a descrição da imagem aqui

Consider the green rectangle the domain of your application (localhost) and the pink rectangle the domain (192.168.1.140) of the HTTP request.

The stream is initialized by an XHR call made by Javascript, the request will be executed normally if:

  • Use GET, HEAD or POST methods;
  • It’s a GET request with no custom headers;
  • It’s a HEAD request with no custom headers;
  • It is a POST request with the header Content-type standard (application/x-www-form-urlencoded, Multipart/form-data or text/Plain) without custom headers.

Unlike simple requests (discussed above), "preflighted" requests first send an HTTP request by the OPTIONS method to the resource in the other domain in order to determine whether the actual request is secure to send, so the server has the opportunity to determine whether to accept a request in these circumstances.

The server in turn responds with headers Access-Control-*, for example:

// indicação de que o dominio "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 all about it. The above information can be checked using, for example, the Google Chrome console, in the tab "Network".

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

I can’t help that part because I don’t know what language is used, if it was imploded or not some framework, etc... However the solution is to accept an HTTP request by the OPTIONS method and return the headers we saw above.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.