HTTP request from javascript using raw message inc

2020-04-17 03:28发布

I know how to make an HTTP request to my REST api from javascript using jQuery or XMLHttpRequest. What I want to do now is make the request without setting properties for the header values. An HTTP request message consists of:

  • Request line, such as GET /images/logo.png HTTP/1.1, which requests a resource called /images/logo.png from server
  • Headers, such as Accept-Language: en
  • An empty line
  • An optional message body

A request to my api should look something like this:

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>

I would like to open a connection to localhost:51127, send the above text, and get the response. Is this possible in javascript?

Update: I know how to set headers. I just want to do it a different way. There are lots of ways to "build" a request including headers and send it. I just want to build it manually.

3条回答
狗以群分
2楼-- · 2020-04-17 03:58

There is no socket support in Javascript. You can only build HTTP queries by using the XMLHTTPRequest wrapper, or optionally wrappers for that such as jQuery.ajax. This is for all kinds of good reasons, principally security.

查看更多
放荡不羁爱自由
3楼-- · 2020-04-17 03:58

Came here looking for same thing. I think it would be possible to build something which takes a raw request text and parses that to an xmlHttpRequest object putting the headers etc in the correct properties. Pls comment a link if something like this already exists. Basically if jQuery has a function to BuildRequestFromRaw(text) that would be awesome.

查看更多
仙女界的扛把子
4楼-- · 2020-04-17 04:11

You can possibly get an instance of the HmlHttpRequest object and use the setRequestHeader.

jQuery has a beforeSend handler you can set to get the actual hxr object.

  $.ajax({
      beforeSend: function(xhr){
          xhr.setRequestHeader("name","value");
       }
  ...
  })
查看更多
登录 后发表回答