【问题标题】:XMLHttpRequest() sends emtpy payloadXMLHttpRequest() 发送空有效载荷
【发布时间】:2021-04-13 18:00:27
【问题描述】:

我遇到了网站问题。我需要使用 XMLHttpRequest 将 GET 请求发送到我在 Node.js 上运行的 api 问题是当我发出请求时它不会发送有效负载。它只是一个空对象。如果我在没有 XMLHttpRequest 的情况下做同样的事情,例如在 Postman 中一切正常。

这是我的 XMLHttpRequest 函数:

// AJAX Client (for RESTful API)
app.client = {}

// Interface for making API calls
app.client.request = function(headers,path,method,queryStringObject,payload,callback){

  // Set defaults
  headers = typeof(headers) == 'object' && headers !== null ? headers : {};
  path = typeof(path) == 'string' ? path : '/';
  method = typeof(method) == 'string' && ['POST','GET','PUT','DELETE'].indexOf(method.toUpperCase()) > -1 ? method.toUpperCase() : 'GET';
  queryStringObject = typeof(queryStringObject) == 'object' && queryStringObject !== null ? queryStringObject : {};
  payload = typeof(payload) == 'object' && payload !== null ? payload : {};
  callback = typeof(callback) == 'function' ? callback : false;

  // For each query string parameter sent, add it to the path
  var requestUrl = path+'?';
  var counter = 0;
  for(var queryKey in queryStringObject){
     if(queryStringObject.hasOwnProperty(queryKey)){
       counter++;
       // If at least one query string parameter has already been added, preprend new ones with an ampersand
       if(counter > 1){
         requestUrl+='&';
       }
       // Add the key and value
       requestUrl+=queryKey+'='+queryStringObject[queryKey];
     }
  }

  // Form the http request as a JSON type
  var xhr = new XMLHttpRequest();
  xhr.open(method, requestUrl, true);
  xhr.setRequestHeader("Content-type", "application/json");

  // For each header sent, add it to the request
  for(var headerKey in headers){
     if(headers.hasOwnProperty(headerKey)){
       xhr.setRequestHeader(headerKey, headers[headerKey]);
     }
  }

  // If there is a current session token set, add that as a header
  if(app.config.sessionToken){
    xhr.setRequestHeader("token", app.config.sessionToken.id);
  }

  // When the request comes back, handle the response
  xhr.onreadystatechange = function() {
      if(xhr.readyState == XMLHttpRequest.DONE) {
        var statusCode = xhr.status;
        var responseReturned = xhr.responseText;

        // Callback if requested
        if(callback){
          try{
            var parsedResponse = JSON.parse(responseReturned);
            callback(statusCode,parsedResponse);
          } catch(e){
            callback(statusCode,false);
          }

        }
      }
  }

  // Send the payload as JSON
  var payloadString = JSON.stringify(payload);
  xhr.send(payloadString);

};

这是我提出请求时的代码:

app.loadCartViewPage = function(){
  var emailAdress = typeof(app.config.sessionToken.emailAdress) == 'string' ? app.config.sessionToken.emailAdress : false;
  if(emailAdress){
    var queryStringObject = { 'emailAdress' : emailAdress };
    app.client.request(undefined, 'api/users', 'GET', queryStringObject, undefined, function(statusCode, responsePayload){
      if(statusCode == 200){
        var cartId = typeof(responsePayload.carts) == 'object' && responsePayload.carts instanceof Array ? responsePayload.carts[0] : [];
        var payload = {'emailAdress' : emailAdress, 'cartId' : cartId };
        app.client.request(undefined, 'api/carts', 'GET', undefined, payload, function(statusCode, responsePayload){
          console.log(responsePayload);
        });
      } else {
        app.logUserOut();
      }
    });
  } else {
    app.logUserOut();
  }
};

第一个 GET 请求按原样通过,我只传递 queryString,但第二个只发送空对象。

提前感谢您的帮助

【问题讨论】:

    标签: javascript node.js json xmlhttprequest


    【解决方案1】:

    XMLHttpRequest 不会为 GET 或 HEAD 请求发送正文。这些请求的参数或选项应该在查询参数中,而不是在正文中。

    这是来自MDN page on .send() 的注释:

    send() 接受一个可选参数,让您指定请求的正文;这主要用于诸如 PUT 之类的请求。如果请求方法是 GET 或 HEAD,则忽略 body 参数,并将请求正文设置为 null。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多