Ajax Javascript Post Authentication Failed

Asked

Viewed 69 times

0

I have an LP that submits a form. I’m taking a test to call a POST when I click Botao to submit a JSON to my API. The JSON is converted. But when you call the $.ajax post it gives ERR_CONNECTION_TIMED_OUT.

inserir a descrição da imagem aqui

Follow the javascript used:

<script type="text/javascript">
var obj = { 
    title: "XXXXXX", 
    stage:{label:"XXXXX"},
    owner:{username:"[email protected]"},
    source:{name:"XXXX"},
    contact:{name:"nameXX", email:"[email protected]", cellphone:"11999999999"},
    openingDate:"2020-03-11T15:30:00.949Z"
};

var dataJson = JSON.stringify(obj);
document.getElementById('btnSubmit').onclick = function(){
    console.log(dataJson);
    $.ajax({
        url: 'http://myurl/rest/endpoint/register',
        method: 'POST',
        dataType : "json",
        headers: {
            'Authorization': 'Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJkZXNlbnZvbHZpbWVudG9AZ3J1cG9lbWlkaWEuY29tIiwiY29tcGFueSI6eyJpZCI6IjVkN2JhNzllNzIxYWQ2MDAwMWZiOGZmNiJ9LCJyb2xJkkI45I6IkFETUlOX1JPTEUiLCJleHAiOjE1ODM5NTM3Nzl9.GafZ7HDOK0Mv_Zu87eKU8St9K8_JfDdyZ2of3ciAguHlTKFGEy2fCkEr3g9PnAxaBADqw2rDqlJSydCuOyIvFg',
        },
        data: dataJson,
        success: function(data){
          console.log('succes: '+data);
        }
    });     
}

  • 1

    Is it because you are sending JSON in string form? Try sending it in object form by parsing: var dataJson = JSON.parse(JSON.stringify(obj));

  • The requisition doesn’t even hit the method there.....

1 answer

0

You can call a function called beforeSend (Before sending) in the AJAX method and set the header in this function. In requests with jquery ajax, it is also advisable to set the property contentType in the request.

See below the example:

$.ajax({
  url: 'http://myurl/rest/endpoint/register',
  method: 'POST',
  dataType: "json",
  contentType: "application/json",
  beforeSend: function (xhr) {
    xhr.setRequestHeader('Authorization', 'Bearer OSEUTOKENAQUI');
  },
  headers: {
    'Authorization': 'Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJkZXNlbnZvbHZpbWVudG9AZ3J1cG9lbWlkaWEuY29tIiwiY29tcGFueSI6eyJpZCI6IjVkN2JhNzllNzIxYWQ2MDAwMWZiOGZmNiJ9LCJyb2xJkkI45I6IkFETUlOX1JPTEUiLCJleHAiOjE1ODM5NTM3Nzl9.GafZ7HDOK0Mv_Zu87eKU8St9K8_JfDdyZ2of3ciAguHlTKFGEy2fCkEr3g9PnAxaBADqw2rDqlJSydCuOyIvFg',
  },
  data: dataJson,
  success: function (data) {
    console.log('succes: ' + data);
  }
});  

Browser other questions tagged

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