0
votes

I'm trying to make a GET request with JSON data using axios to aspnet core like so

  axios.get("http://localhost/api/tag/getnearby",{
     Latitude:24.470901,
     Longitude:39.612236,
     RangeInMeters:5000
  },{
     headers: {
        'Content-Type': 'application/json;charset=UTF-8',
        'Access-Control-Allow-Origin': true,
        'Access-Control-Request-Headers': 'Content-Type, x-requested-with',
     }
  })
  .then(response => {
     console.log(response)
  })
  .catch(err =>  {
     console.log(err)
  })

Backend

[HttpGet("getnearby")]
[AllowAnonymous]
public ActionResult GetNearby(GetNearbyRequest request)
{
    var tags = Tag.SelectNearby(Convert.ToDouble(request.Longitude),Convert.ToDouble(request.Latitude),Convert.ToUInt32(request.RangeInMeters));
    return Ok(new {tags = tags});
}


public class GetNearbyRequest
{
    public string Latitude {get;set;}
    public string Longitude {get;set;}
    public string RangeInMeters {get;set;}
}

However I always get 415 Unsupported media type error in the response and the compiler doesn't hit a breakpoint inside the ActionResult.

The weired thing is I've tried to do the same request from an api client like Insomnia or PostMan and it worked fine.

Thanks in advance

1
Why are you sending Content-Type in a GET request? - Julian Reschke
Tried to mimic the headers from the insomnia api client, thought it could help. - Mawardy

1 Answers

1
votes

With axios get method, the parameters passed to the background are string, it can not pass json, post method can realize.

You can add [FromQuery] in backend.

    public ActionResult GetNearby([FromQuery]GetNearbyRequest request)
    {
        //...
        return Ok(request);
    }

And the method get in axios should add params.

axios.get("https://localhost:44350/api/Tag/getnearby",
        {params:{
                Latitude:24.470901,
                Longitude:39.612236,
                RangeInMeters:5000
              }},{
                headers: {
                    'Content-Type': 'application/json;charset=UTF-8',
                    'Access-Control-Allow-Origin': true,
                    'Access-Control-Request-Headers': 'Content-Type, x-requested-with',
                }
              })
              .then(response => {
                console.log(response)
              })
              .catch(err =>  {
                console.log(err)
              })
            }

The result returned by the backend.

enter image description here