来自javascript的HTTP请求使用包括标头的原始消息

时间:2010-12-23 17:43:16

标签: javascript jquery http rest http-headers

我知道如何使用jQuery或XMLHttpRequest从javascript向我的REST api发出HTTP请求。我现在要做的是在不设置标题值属性的情况下发出请求。 HTTP request message包含:

  
      
  • 请求行,例如GET /images/logo.png HTTP / 1.1,它从服务器请求名为/images/logo.png的资源
  •   
  • 标题,例如Accept-Language:en
  •   
  • 空行
  •   
  • 可选的邮件正文
  •   

对我的api的请求应该是这样的:

GET /myapi/myresource/1234 HTTP/1.1
Host: localhost:51127
Content-Type: application/x-www-form-urlencoded
Accept: application/json, text/csv
Authorization: Basic <base64 encoded credentials>

我想打开一个到localhost的连接:51127,发送上面的文字,然后得到回复。这可以在javascript中使用吗?

  

更新:我知道如何设置标头。一世   只想以不同的方式做到这一点。   有很多方法可以“建立”a   请求包括标题并发送它。   我只是想手动构建它。

4 个答案:

答案 0 :(得分:2)

您可以获取HmlHttpRequest对象的实例并使用setRequestHeader。

jQuery有一个beforeSend处理程序,你可以设置它来获取实际的hxr对象。

  $.ajax({
      beforeSend: function(xhr){
          xhr.setRequestHeader("name","value");
       }
  ...
  })

答案 1 :(得分:2)

Javascript中没有套接字支持。您只能使用XMLHTTPRequest包装器构建HTTP查询,或者选择包含 的包装器,例如jQuery.ajax。这是出于各种好的理由,主要是安全性。

答案 2 :(得分:1)

要以孤独某日的答案为基础,以下是实际操作方法。

function rawRequest(txt,cb) {
  let x = new XMLHttpRequest(),
      lines = txt.split("\n"),
      methods = [
        "GET",
        "POST",
        "PATCH",
        "PUT",
        "DELETE",
        "HEAD",
        "OPTIONS"
      ],
      host, path, method, version, body = "", headers = {}
  lines.forEach((x, i) => {
    if(!x.includes(":")) {
      let ind;
      methods.forEach(m => {
        let tmpIndex = x.indexOf(m);
        
        if(tmpIndex > -1) {
          if(!method) {
            ind = tmpIndex;
            let words = x.split(" ");
            method = x.substring(
              tmpIndex,
              tmpIndex + 
              m.length
            );
            method = method && method.trim();
            path = words.find((y, k) => 
              y[0] === "/"
            )
            path = path && path.trim();
            version = (
              x
              .replace(method, "")
              .replace(path, "")
            ).trim();
          }
          
        }
      });
    } else {
      let indexOfSemiColon = x.indexOf(":");
      if(
        indexOfSemiColon > 0 &&
        indexOfSemiColon < x.length - 1
      ) {
      
        let key = x.substring(
          0,
          indexOfSemiColon
        ).trim(),
            value = x.substring(
              indexOfSemiColon + 1
            ).trim();
         headers[key] = value;
         if(key.toLowerCase() == "host") {
          host = value
         }
   	 }
    }
  });
  let inds = []
  txt.split(/\r?\n/).forEach((x,i)=>
    x === "" 
    && inds.push(i)
  )
  let afterTwoLineBreaksIndex;
  inds.forEach((x,i) => {
    if(
      i < inds.length - 2 &&
      inds[i] === "" &&
      inds[i + 1] === ""
    ) {
      afterTwoLineBreaksIndex = i + 1;
    }
  });
  if(afterTwoLineBreaksIndex) {
    body = txt.substring(
      afterTwoLineBreaksIndex
    )
  }
  x.onreadystatechange = () => {
    if(x.readyState == 4 && x.status == 200) {
      if(cb) cb(x.response);
    } 
  }
  if(host && path && method) {
    x.open(
      method, 
      "http://" //don't know how to differentiate between http & https, if some1 could help out would be greate
      + host 
      + path
    );
    
    for(let k in headers) {
      x.setRequestHeader(k, headers[k]);
    }
    
    x.send(body);
  }
  return {
    headers,
    body,
    method,
    host,
    path,
    version
  } //for testing just return all the values we found
}

console.log(
  rawRequest(`
    GET /search?q=test HTTP/2
    Host: www.bing.com
    User-Agent: curl/7.54.0
    Accept: */*`
  ),
  rawRequest(`
    GET /foo/bar HTTP/1.1
    Host: example.org
    User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; fr; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8
    Accept: */*
    Accept-Language: fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3
    Accept-Encoding: gzip,deflate
    Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
    Keep-Alive: 115
    Connection: keep-alive
    Content-Type: application/x-www-form-urlencoded
    X-Requested-With: XMLHttpRequest
    Referer: http://example.org/test
    Cookie: foo=bar; lorem=ipsum;
  `),
   rawRequest(`
      GET /myapi/myresource/1234 HTTP/1.1
      Host: localhost:51127
      Content-Type: application/x-www-form-urlencoded
      Accept: application/json, text/csv
      Authorization: Basic <base64 encoded credentials>
   `)
  
 )

答案 3 :(得分:0)

来这里寻找相同的东西。我认为有可能构建一些将原始请求文本并解析为xmlHttpRequest对象的东西,从而将标头等置于正确的属性中。如果这样的链接已经存在,请给链接添加注释。基本上,如果jQuery有一个很棒的BuildRequestFromRaw(text)函数。