Home > Mobile >  curl GET request works but not axios
curl GET request works but not axios

Time:02-04

I am trying to set up my elasticsearch server through docker using this command:

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

When I make a request to it using curl, it works:

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":[]}}%

However, in my react code I am trying to use axios to make the same request but all I get is CORS errors

    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);
    }

enter image description here

How can I fix this?

CodePudding user response:

There are some missing parts in your docker run command. You can try following the example.

version: '3'
services:
  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:7.17.8
    container_name: elasticsearch-ui
    environment:
      - discovery.type=single-node
      - http.cors.allow-origin=*
      - http.cors.enabled=true
      - http.cors.allow-credentials=true
      - http.cors.allow-methods=OPTIONS, HEAD, GET, POST, PUT, DELETE
      - http.cors.allow-headers=X-Requested-With, X-Auth-Token, Content-Type, Content-Length, Authorization, Access-Control-Allow-Headers, Accept, x-elastic-client-meta
    ports:
      - 9200:9200
      - 9300:9300
  kibana:
    image: docker.elastic.co/kibana/kibana:7.17.8
    container_name: kibana-ui
    ports:
      - 5601:5601
    depends_on:
      - elasticsearch
  • Related