簡體   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