使用axios将请求发送到Elasticsearch

编程入门 行业动态 更新时间:2024-10-27 23:19:05
本文介绍了使用axios将请求发送到Elasticsearch的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在开发一个React应用,该应用需要从elsaticsearch获取数据. 在前端,实际上我正在尝试使用axios进行请求:

I'm working on a react app which needs to fetch data from elsaticsearch. In frontend, actually I'm trying to use axios to do the request:

const query = { query: { match: { "_id": "AV12n5KzsohD5gXzTnOr" } } }; axios.get('localhost:9200/my-index/my-type/_search', query) .then((res) => { console.log(res); });

我想获取带有某些ID的特定文档.上面的查询实际上在kibana内部有效.但是,上面的查询返回了my-type内的所有文档,我在这里做错了什么?

I want to get the specific document with some ID. The above query actually works inside kibana. However, the above query returns all the documents inside my-type, what am I doing wrong here?

推荐答案

我认为下面的方法应该有效.尽管 Axios自述文件指出data仅专门用于PUT,POST和PATCH请求,我在执行此操作的代码中没有看到任何内容,并且经过简化的测试表明,确实为GET请求发送了请求正文:

I think the below should work. Although the Axios README says that data is specifically only for PUT, POST, and PATCH requests, I didn't see anything in the code that enforces this, and a simplified test shows that the request body is indeed sent for GET requests:

axios.get('localhost:9200/my-index/my-type/_search', { data: JSON.stringify(query), }).then((res) => { console.log(res); });

编辑

请注意,我仅在Node.js中进行了测试,而没有在浏览器中进行过测试.浏览器可能不太愿意包含带有GET请求的请求正文.

Note that I've only tested this in Node.js, not in a browser. Browsers may be less inclined to include request bodies with GET requests.

编辑2

Elasticsearch似乎允许发送请求正文而不是参数中,也许是因为这个问题.

Elasticsearch seems to allow sending the request body in a parameter instead, perhaps because of this very issue.

这应该可以解决问题:

axios.get('localhost:9200/my-index/my-type/_search', { params: { source: JSON.stringify(query), source_content_type: 'application/json' } }).then((res) => { console.log(res); });

编辑3

的确,这确实是在浏览器中发出GET请求的一般限制.根据 XMLHttpRequest.send的文档:

This does indeed seem to be a general restriction on making GET requests in browsers. Per the documentation for XMLHttpRequest.send:

如果请求方法是GET或HEAD,则将忽略参数并将请求正文设置为null.

If the request method is GET or HEAD, the argument is ignored and request body is set to null.

更多推荐

使用axios将请求发送到Elasticsearch

本文发布于:2023-10-11 22:16:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1482992.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:发送到   axios   Elasticsearch

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!