404 в JQuery Ajax POST вызов при отправке XML на сервер - PullRequest
0 голосов
/ 26 сентября 2019

Я недавно работаю с расширениями Adobe InDesign и хочу загрузить файл XML на мой сервер с помощью вызова jostery ajax POST, поэтому для этого мне нужно прочитать файл XML из файловой системы и сохранить его в переменной.и затем передайте эту переменную как тело в запрос на отправку. Вот мой код

function uploadDocument( onSuccess, onError, onComplete) {
  var token = localStorage.getItem("token");
  writeLogs("uploadDocument function \n " + token );

  var result = window.cep.fs.readFile("/Users/mac41589/Downloads/test-xmls/post.xml");
  var xmlStr = "";

  if(result.err == 0){
    writeLogs("file read complete " + ' ' + result.data)
    xmlStr = result.data;
    alert("type of xmlStr new" + ' ' + typeof(xmlStr));

    $.ajax({
      url : "https://xyz.abc.com/capi-demo/article?customerNumber=888",
      method: "POST",
      data: xmlStr,
      beforeSend : function(xhr) {
        xhr.setRequestHeader("Authorization", "Bearer " + token);
        xhr.setRequestHeader("Content-Type", "application/xml");
      },
      complete: function(xhr) {
          alert("on complete with code" + ' ' + xhr.status + ' ' + xhr.statusText );
          //onComplete();
      },
      success : function(response) { 
          alert("file upload success with response : " + ' ' +response);
      },
      error : function(jqXHR, textStatus, errorThrown) {
          alert('file upload fail with error -- ' + jqXHR.status + ' textStatus: ' + textStatus + ' errorThrown: ' + errorThrown);
      }
    });
  }
}

, а здесь точный XML-файл, который я хочу отправить:

<document xmlns="http://pubpress.com/document">
   <properties>
       <magazineNumber>95100</magazineNumber>
   </properties>
   <article>
       <pam:message xmlns:pam="http://xax.org/namespaces/pam/2.0/" xmlns:ppc="http://axa.com/content" xml:base="/article/content/39992.xml">
   <pam:article>
       <head xmlns="http://www.w3.org/1999/xhtml">
           <dc:identifier xmlns:dc="http://purl.org/dc/elements/1.1/">888-create.xml</dc:identifier>
           <pam:status/>

       </head>
       <body xmlns="http://www.w3.org/1999/xhtml"><p>Sample body text</p></body>
   </pam:article>
</pam:message>
   </article>
</document>

, поэтому всякий раз, когда я выполняю этоВызов POST возвращает ошибку 404 Not Found, но когда я отправляю неправильный (нежелательный для сервера) XML-файл, он показывает 400 неверных запросов.неправильный xml (нежелательный для сервера) выглядит следующим образом:

<?xml version="1.0" encoding="UTF-8"?>
<variable type="NameValuePair[]">
   <item type="NameValuePair">
      <name type="String"><![CDATA[No Data Found]]></name>
      <value type="String"><![CDATA[95990070]]></value>
   </item>
</variable>

Я не могу выяснить, почему этот вызов POST возвращает 404 из вызова ajax, где тот же вызов с такими же параметрами хорошо работает в PostMan.заранее спасибо. Любая помощь по этому вопросу будет высоко оценен.

1 Ответ

0 голосов
/ 26 сентября 2019

Кроме того, чтобы убедиться, что URL-адрес принимает опубликованные xml, вы должны добавить опцию ajax для contentType: "text/xml", в вашу конфигурацию.

Здесь я вывожу вещи из глобальной области видимости с myApp (не часть вопроса, но для меня это лучше на практике).Я снова переориентировался на форму обещания .ajax(), потому что она мне больше нравится, и я мог бы затем заменить функции там на некоторый обработчик ошибок с именами пространств для всех моих ajax, например (это те, что передаются, обратные вызовы?)

Я также увидел там пару багов типа typeof().Это предполагает ES6.

// create a namespace object
var myApp = myApp || {
  url: "https://xyz.abc.com/capi-demo/article?customerNumber=888"
};
// borrow some code from https://stackoverflow.com/a/23861977/125981
myApp.isXHR = function(maybe) {
  if (!maybe) {
    return false;
  }
  if (!('readyState' in maybe)) {
    return false;
  }
  if (!('responseText' in maybe)) {
    return false;
  }
  if (!('status' in maybe)) {
    return false;
  }
  if (!('statusText' in maybe)) {
    return false;
  }
  return true;
};

myApp.writeLogs = function(logmessage) {
  // just to act as placeholder for the answer
};

myApp.processMessage = function(message, silent = true) {
  if (silent) {
    alert(message);
  } else { // or
    console.log(message);
    // or something else like send to server via ajax to log or some such
  }
};

myApp.getDocumentContent = function() {

  let result = window.cep.fs.readFile("/Users/mac41589/Downloads/test-xmls/post.xml");
  //var xmlStr = "";
  let getResult = {
    xmlStr: "",
    hasContent: false,
    error: result.err
  };
  if (result.err == 0) {
    myApp.writeLogs("file read complete " + ' ' + result.data)
    myApp.processMessage("type of xmlStr new" + ' ' + (typeof result.data));
    getResult.xmlStr = result.data;
    getResult.hasContent = true;
  }
  return getResult;
};

myApp.sendContent = function(contentObj) {
  let token = localStorage.getItem("token");
  myApp.writeLogs("uploadDocument function \n " + token);
  myApp.writeLogs("file read complete " + contentObj.xmlStr);
  myApp.processMessage("type of xmlStr new " + (typeof contentObj.xmlStr));

  $.ajax({
      url: myApp.url,
      method: "POST",
      data: contentObj.xmlStr,
      contentType: "text/xml",
      beforeSend: function(xhr, settings) {
        xhr.setRequestHeader("Authorization", "Bearer " + token);
        xhr.setRequestHeader("Content-Type", "application/xml");
      }
    })
    .always(function(dataOrJqXHR, textStatus, jqXHROrErrorThrown) {
      // determine which parameter is which when the .always() is called
      let my_jqXHR = null;
      let data = null;
      let errorThrown = null;
      if (myApp.isXHR(dataOrJqXHR)) {
        my_jqXHR = dataOrJqXHR;
        errorThrown = jqXHROrErrorThrown;
      }
      if (myApp.isXHR(jqXHROrErrorThrown)) {
        my_jqXHR = jqXHROrErrorThrown;
        data = dataOrJqXHR;
      }
      let status = my_jqXHR.status;
      // do something with status
      myApp.processMessage("on complete with code" + ' ' + status + ' ' + errorThrown);
    })
    .done(function(data, textStatus, jqXHR) {
      myApp.processMessage("file upload success with response : " + ' ' + textStatus + ' ' + data);
    })
    .fail(function(jqXHR, textStatus, errorThrown) {
      myApp.processMessage('file upload fail with error -- ' + jqXHR.status + ' textStatus: ' + textStatus + ' errorThrown: ' + errorThrown);
    })
    .then(function(data, textStatus, jqXHR) {
      myApp.processMessage("file upload success with response : " + ' ' + textStatus + ' ' + data);
    }, function(jqXHR, textStatus, errorThrown) {
      myApp.processMessage('file upload fail with error -- ' + jqXHR.status + ' textStatus: ' + textStatus + ' errorThrown: ' + errorThrown);
    });
};

myApp.uploadDocument = function(onSuccess, onError, onComplete) {
  let contentObj = myApp.getDocumentContent();

  if (contentObj.hasContent && contentObj.err == 0) {
    myApp.sendContent(contentObj);
  } else {
    myApp.processMessage("No Content" + contentObj.err);
  }
};
// call it, not sure what these passed thing are, and seem unused
myApp.uploadDocument(onSuccess, onError, onComplete);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
...