You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

curl请求Elasticsearch正常但Axios报CORS错误,如何解决?

解决React中Axios请求Elasticsearch的CORS错误

问题场景

我通过以下Docker命令部署Elasticsearch 8.6.1服务器:

docker run \
       -p 9200:9200 \
       -p 9300:9300 \
       -e "discovery.type=single-node" \
       -e "xpack.security.enabled=false" \
       -e "http.cors.allow-credentials=true" \
       -e "http.cors.allow-headers=Access-Control-Allow-Origin,x-csrf-token,authorization,content-type,accept,origin,x-requested-with" \
       -e "http.cors.allow-origin=http://localhost:3100" \
       docker.elastic.co/elasticsearch/elasticsearch:8.6.1

使用curl发送GET请求可正常获取响应:

myapp - (main) $ curl -XGET "http://localhost:9200/_search" -H "Origin: http://example.com" -H "Content-Type: application/json" -d'
{
  "query": {
    "match_all" : {}
  }
}'
{"took":0,"timed_out":false,"_shards":{"total":0,"successful":0,"skipped":0,"failed":0},"hits":{"total":{"value":0,"relation":"eq"},"max_score":0.0,"hits":[]}}%

但在React代码中使用Axios发送相同请求时,始终出现CORS错误,Axios代码如下:

try {
  const res = await axios.get('http://localhost:9200/_search', {
    data: JSON.stringify({
      query: {
        match_all: {},
      },
    }),
    headers: {
      'Content-Type': 'application/json',
    },
  });
  console.log('response: ', res.data);
} catch (e) {
  console.log('eeeeeeeeeee', e);
}

CORS错误截图:
CORS错误截图


解决方案

1. 修正Elasticsearch的CORS允许源配置

当前http.cors.allow-origin仅允许http://localhost:3100,但React开发环境默认运行在http://localhost:3000,需修改该配置匹配你的React项目端口:

docker run \
       -p 9200:9200 \
       -p 9300:9300 \
       -e "discovery.type=single-node" \
       -e "xpack.security.enabled=false" \
       -e "http.cors.allow-credentials=true" \
       -e "http.cors.allow-headers=x-csrf-token,authorization,content-type,accept,origin,x-requested-with" \
       -e "http.cors.allow-origin=http://localhost:3000" \ # 替换为你的React项目实际端口
       docker.elastic.co/elasticsearch/elasticsearch:8.6.1

开发环境临时测试可使用"*"允许所有源,但生产环境务必指定具体域名

2. 修正Axios请求的写法

GET请求携带请求体并非HTTP标准规范,部分浏览器或客户端会处理异常。Elasticsearch的/_search接口支持POST请求,建议改用POST发送查询体:

try {
  const res = await axios.post('http://localhost:9200/_search', {
    query: {
      match_all: {},
    },
  }, {
    headers: {
      'Content-Type': 'application/json',
    },
  });
  console.log('response: ', res.data);
} catch (e) {
  console.log('eeeeeeeeeee', e);
}

3. 清理无效的CORS头配置

原配置中http.cors.allow-headers包含Access-Control-Allow-Origin,这是服务器响应头,不属于客户端请求头范畴,需移除该条目,避免CORS校验异常。


内容的提问来源于stack exchange,提问作者bigpotato

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 12:40:21