简体   繁体   English

尝试将多个 arguments 传递给带有 axios 的 React 中的 get 请求时出现 415 错误

[英]Getting 415 error when trying to pass in multiple arguments to a get request in React with axios

This might be easy (or hard) to answer, I'm new to react but haven't found a solution to my problem.这可能很容易(或很难)回答,我是新手,但还没有找到解决我问题的方法。

I made an api that looks like this:我做了一个看起来像这样的 api:

[HttpGet]
[Route("GetDateRange")]
public IActionResult GetDateRange(DateRangeModel model)
{
 ...
}

So it takes in a DateRangeModel object.所以它需要一个 DateRangeModel object。 This object simply looks like this:这个 object 看起来像这样:

public class DateRangeModel
{
    public int PlayerId { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
}

Now on the frontend, in react, I always seem to get a 415 (unsupported media error) no matter how I try to pass in the values.现在在前端,作为反应,无论我如何尝试传递值,我似乎总是得到 415(不支持的媒体错误)。 Here is my latest attempt with some hardcoded values:这是我对一些硬编码值的最新尝试:

var body = {
    playerId: 2, 
    startDate: '2020-01-01',
    endDate: '2020-03-03'
};

var myJson = JSON.stringify(body);

const result = await axios.get('http://localhost:64390/api/players/getdaterange/', myJson);
console.log(result);

When I enter this in the body in Postman it works perfectly and I get the 200 OK message along with the correct json response:当我在 Postman 的正文中输入它时,它工作得很好,我收到 200 OK 消息以及正确的 json 响应:

{
    "playerId": 2,
    "startDate": "2020-01-01",
    "endDate": "2020-03-03"
}

Thank you for any help.感谢您的任何帮助。

Well, because you are sending data to server you will have to use a post request.好吧,因为您正在向服务器发送数据,所以您将不得不使用post请求。 Right now you are using axios.get and you will need to replace it with axios.post.现在您正在使用 axios.get,您需要将其替换为 axios.post。 And you don't even need to use JSON.stringify method to parse the object into a string before axios.post method.而且您甚至不需要在 axios.post 方法之前使用 JSON.stringify 方法将 object 解析为字符串。 Let me give a demonstration;让我做一个示范;


axios.post('http://localhost:64390/api/players/getdaterange/', {
    playerId: 2, 
    startDate: '2020-01-01',
    endDate: '2020-03-03'
})
.then((response) => {
  console.log(response);
}, (error) => {
  console.log(error);
});


And you would need to handle this request on your server with a post request handler.并且您需要使用post请求处理程序在您的服务器上处理此请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM