繁体   English   中英

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

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

这可能很容易(或很难)回答,我是新手,但还没有找到解决我问题的方法。

我做了一个看起来像这样的 api:

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

所以它需要一个 DateRangeModel object。 这个 object 看起来像这样:

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

现在在前端,作为反应,无论我如何尝试传递值,我似乎总是得到 415(不支持的媒体错误)。 这是我对一些硬编码值的最新尝试:

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

当我在 Postman 的正文中输入它时,它工作得很好,我收到 200 OK 消息以及正确的 json 响应:

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

感谢您的任何帮助。

好吧,因为您正在向服务器发送数据,所以您将不得不使用post请求。 现在您正在使用 axios.get,您需要将其替换为 axios.post。 而且您甚至不需要在 axios.post 方法之前使用 JSON.stringify 方法将 object 解析为字符串。 让我做一个示范;


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


并且您需要使用post请求处理程序在您的服务器上处理此请求。

暂无
暂无

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

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