简体   繁体   English

使用 jQuery $.ajax() 时如何使用 GET 在请求正文中发送数据

[英]How to send data in request body with a GET when using jQuery $.ajax()

The service API I am consuming has a given GET method that requires the data be sent in the body of the request.我正在使用的服务 API 具有给定的 GET 方法,该方法要求在请求正文中发送数据。

The data required in the body is a list of id's separated by hypen and could potentially be very large and thus it must be sent in the body otherwise it will likely foobar somewhere in the browsers/proxies/webservers etc chain.正文中所需的数据是由 hypen 分隔的 id 列表,可能非常大,因此它必须在正文中发送,否则它可能会在浏览器/代理/网络服务器等链中的某个地方出现 foobar。 Note I don't have control over the service or API so please don't make suggestions to change it.请注意,我无法控制该服务或 API,因此请不要提出更改它的建议。

I am using the following jQuery code however observing the request/response in fiddler I can see that the "data" I am sending is ALWAYS converted and appended to the query string despite me setting the "processData" option to false...我正在使用以下 jQuery 代码但是观察提琴手中的请求/响应我可以看到我发送的“数据”总是被转换并附加到查询字符串,尽管我将“processData”选项设置为 false ...

$.ajax({
   url: "htttp://api.com/entity/list($body)",
   type: "GET",
   data: "id1-id2-id3",
   contentType: "text/plain",
   dataType: "json",
   processData: false, // avoid the data being parsed to query string params
   success: onSuccess,
   error: onError
});

Anyone know how I can force the "data" value to be sent in the body of the request?任何人都知道我如何强制在请求正文中发送“数据”值?

In general, that's not how systems use GET requests.通常,这不是系统使用 GET 请求的方式。 So, it will be hard to get your libraries to play along.所以,很难让你的图书馆一起玩。 In fact, the spec says that "If the request method is a case-sensitive match for GET or HEAD act as if data is null."事实上,规范说“如果请求方法是区分大小写的 GET 或 HEAD 匹配,就好像数据是 null。” So, I think you are out of luck unless the browser you are using doesn't respect that part of the spec.所以,我认为你运气不好,除非你使用的浏览器不遵守规范的那一部分。

You can probably setup an endpoint on your own server for a POST ajax request, then redirect that in your server code to a GET request with a body.您可以在自己的服务器上为 POST ajax 请求设置一个端点,然后在您的服务器代码中将其重定向到带有正文的 GET 请求。

If you aren't absolutely tied to GET requests with the body being the data, you have two options.如果您不完全依赖于以正文作为数据的 GET 请求,您有两种选择。

POST with data: This is probably what you want. POST with data:这可能是你想要的。 If you are passing data along, that probably means you are modifying some model or performing some action on the server.如果你正在传递数据,那可能意味着你正在修改一些 model 或在服务器上执行一些操作。 These types of actions are typically done with POST requests.这些类型的操作通常通过 POST 请求完成。

GET with query string data: You can convert your data to query string parameters and pass them along to the server that way.使用查询字符串数据获取:您可以将数据转换为查询字符串参数,并以这种方式将它们传递给服务器。

url: 'somesite.com/models/thing?ids=1,2,3'

we all know generally that for sending the data according to the http standards we generally use POST request.众所周知,按照http标准发送数据,我们一般使用POST请求。 But if you really want to use Get for sending the data in your scenario I would suggest you to use the query-string or query-parameters.但是如果你真的想在你的场景中使用 Get 发送数据,我建议你使用查询字符串或查询参数。

1.GET use of Query string as . 1.GET 使用查询字符串作为. {{url}}admin/recordings/some_id

here the some_id is mendatory parameter to send and can be used and req.params.some_id at server side.这里的some_id是要发送的强制参数,可以在服务器端使用和req.params.some_id

2. GET use of query string as {{url}}admin/recordings?durationExact=34&isFavourite=true 2. GET 使用查询字符串作为{{url}}admin/recordings?durationExact=34&isFavourite=true

here the durationExact,isFavourite is optional strings to send and can be used and req.query.durationExact and req.query.isFavourite at server side.这里的 durationExact,isFavourite 是要发送的可选字符串,可以在服务器端使用req.query.durationExactreq.query.isFavourite

3. GET Sending arrays {{url}}admin/recordings/sessions/?os["Windows","Linux","Macintosh"] 3. GET 发送 arrays {{url}}admin/recordings/sessions/?os["Windows","Linux","Macintosh"]

and you can access those array values at server side like this您可以像这样在服务器端访问这些数组值

let osValues = JSON.parse(req.query.os);
        if(osValues.length > 0)
        {
            for (let i=0; i<osValues.length; i++)
            {
                console.log(osValues[i])
                //do whatever you want to do here
            }
        }

You know, I have a not so standard way around this.你知道,我有一个不太标准的方法来解决这个问题。 I typically use nextjs.我通常使用 nextjs。 I like to make things restful if at all possible.如果可能的话,我喜欢让事情变得平静。 If I need to make a get request I instead use post and in the body I add a submethod parameter which is GET.如果我需要发出 get 请求,我会改用 post 并在正文中添加一个 GET 子方法参数。 At which point my server side handles it.此时我的服务器端处理它。 I know it's still a post method technically but this makes the intention clear and I don't need to add any query parameters.我知道它在技术上仍然是一个 post 方法,但这使得意图很明确,我不需要添加任何查询参数。 Then the get method handles a get request using the data provided in the post method.然后 get 方法使用 post 方法中提供的数据处理 get 请求。 Hopefully this helps.希望这会有所帮助。 It's a bit of a side step around proper protocol but it does mean there's no crazy work around and the code on the server side can handle it without any problems.这有点绕过正确的协议,但它确实意味着没有疯狂的变通办法,服务器端的代码可以毫无问题地处理它。 The first thing present in the server side is if(subMethod === "GET"){|DO WHATEVER YOU NEED|}服务器端出现的第一件事是 if(subMethod === "GET"){|DO WHATEVER YOU NEED|}

Just in case somebody ist still coming along this question:以防万一有人仍然提出这个问题:

There is a body query object in any request.任何请求中都有一个body query object。 You do not need to parse it yourself.您不需要自己解析它。

Eg if you want to send an accessToken from a client with GET, you could do it like this:例如,如果您想使用 GET 从客户端发送 accessToken,您可以这样做:

 const request = require('superagent'); request.get(`http://localhost:3000/download?accessToken=${accessToken}`).end((err, res) => { if (err) throw new Error(err); console.log(res); });

The server request object then looks like {request: {... query: { accessToken: abcfed }... } }服务器请求 object 然后看起来像{request: {... query: { accessToken: abcfed }... } }

The service API I am consuming has a given GET method that requires the data be sent in the body of the request.我正在使用的服务API具有给定的GET方法,该方法要求在请求的正文中发送数据。

The data required in the body is a list of id's separated by hypen and could potentially be very large and thus it must be sent in the body otherwise it will likely foobar somewhere in the browsers/proxies/webservers etc chain.正文中所需的数据是用连字符分隔的ID列表,并且可能非常大,因此必须在正文中发送,否则可能会在浏览器/代理/网络服务器等链中的某处出现foobar。 Note I don't have control over the service or API so please don't make suggestions to change it.注意:我无法控制服务或API,因此请不要提出更改建议。

I am using the following jQuery code however observing the request/response in fiddler I can see that the "data" I am sending is ALWAYS converted and appended to the query string despite me setting the "processData" option to false...我正在使用以下jQuery代码,但是在提琴手中观察请求/响应,尽管我将“ processData”选项设置为false,但我仍然可以看到正在发送的“数据”始终被转换并附加到查询字符串中。

$.ajax({
   url: "htttp://api.com/entity/list($body)",
   type: "GET",
   data: "id1-id2-id3",
   contentType: "text/plain",
   dataType: "json",
   processData: false, // avoid the data being parsed to query string params
   success: onSuccess,
   error: onError
});

Anyone know how I can force the "data" value to be sent in the body of the request?有谁知道我可以如何强制在请求正文中发送“数据”值? Any assistance is appreciated, thanks in advance.感谢您的任何帮助,在此先感谢您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM