使用axios将请求发送到Elasticsearch [英] Sending requests to Elasticsearch with axios

查看:363
本文介绍了使用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('http://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仅专门用于PUTPOSTPATCH请求,我在执行此操作的代码中没有看到任何内容,并且经过简化的测试表明,确实为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('http://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('http://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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆