【问题标题】:Getting 415 error when trying to pass in multiple arguments to a get request in React with axios尝试使用 axios 将多个参数传递给 React 中的 get 请求时出现 415 错误
【发布时间】:2020-05-07 19:29:11
【问题描述】:

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

我做了一个如下所示的api:

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

所以它接受一个 DateRangeModel 对象。这个对象看起来像这样:

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"
}

感谢您的帮助。

【问题讨论】:

    标签: javascript reactjs http axios


    【解决方案1】:

    好吧,因为您要向服务器发送数据,所以您必须使用post 请求。现在你正在使用 axios.get,你需要用 axios.post 替换它。而且您甚至不需要在 axios.post 方法之前使用 JSON.stringify 方法将对象解析为字符串。让我来演示一下;

    
    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 请求处理程序处理此请求。

    【讨论】:

    • 但是我会得到 405 方法不允许。或者我应该将我的 api 更改为 Post 而不是 Get?
    • 谢谢,它现在适用于发布请求。我不知道为什么我没有想到这样做,我想我只是假设因为我没有更新我应该使用 get 的数据库。
    • @JEvansPritchard 无论您使用哪种 http 方法,您都必须使用完全相同的方法在您的 api 端点处理它。这与语言或任何框架无关。这就是网络的运作方式
    • @JEvansPritchard 非常感谢 :)
    • @JEvansPritchard 同样在这里!
    猜你喜欢
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    • 2018-07-30
    • 2020-10-17
    • 2015-08-27
    • 2021-08-24
    • 2020-02-25
    相关资源
    最近更新 更多