簡體   English   中英

Axios HTTP DELETE請求返回415錯誤

[英]Axios HTTP DELETE request returns 415 error

我正在按照教程課程構建一個以 ASP.NET 核心作為后端的 React.js 應用程序。 我正在使用 Axios 來處理 HTTP 請求,我測試了 get、post、put 請求工作正常,但在 del 請求期間不斷出錯。 這是產生相同錯誤的簡化 function:

  const handleDeleteActivityTest = () => {
    Axios.delete('https://localhost:5001/api/activities/e2beb0eb-eaaa-49ee-92d8-daf472210456');
  }

該請求在控制台中打印以下錯誤消息:

刪除https://localhost:5001/api/activities/e2beb0eb-eaaa-49ee-92d8-daf472210456 415(不支持的媒體類型)

createError.js:16 Uncaught (in promise) 錯誤:在 XMLHttpRequest.handleLoad (xhr.js:61) 處結算 (settle.js:17) 處的 createError (createError.js:16) 請求失敗,狀態碼為 415

但是我在 Postman 中進行了測試,刪除請求工作正常並返回 200 OK 響應,我可以在數據庫中看到該條目被刪除:

Postman DELETE 響應

如果有人可以教育我這里發生了什么,我將不勝感激。 謝謝你,保持安全和快樂。

編輯 - - - - - - - - - - - - - - - - -

這是處理 HTTP 請求的后端代碼。 它分為兩部分——1.)接收 HTTP 請求的 controller 和 2.)處理它的 MediatR class:

1.)

namespace API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ActivitiesController : ControllerBase
    {
        private readonly IMediator _mediator;

        public ActivitiesController(IMediator mediator)
        {
            _mediator = mediator;
        }

        [HttpDelete("{id}")]
        public async Task<ActionResult<Unit>> Delete(Guid id, Delete.Command command)
        {
            command.Id = id;
            return await _mediator.Send(command);
        }
    }
}

2.)

namespace Application.Activities
{
    public class Delete
    {
        public class Command : IRequest
        {
            public Guid Id { get; set; }
        }

        public class Handler : IRequestHandler<Command>
        {
            private readonly DataContext _context;

            public Handler(DataContext context)
            {
                _context = context;
            }

            public async Task<Unit> Handle(Command request, CancellationToken cancellationToken)
            {
                var activity = await _context.Activities.FindAsync(request.Id);

                if (activity == null)
                    throw new Exception("Could not find activity");

                _context.Remove(activity);



                var success = await _context.SaveChangesAsync() > 0;

                if (success) return Unit.Value;

                throw new Exception("Problem saving changes");
            }
        }
    }
}

I found that the HttpDelete method in the controller receives id as a Guid, but in the React app id is typed as string, so I changed the type to string in the controller and MediatR class, but same http error 415.

Axios 在刪除調用時不發送內容類型 看起來 ASP.net 內核想要一個content-type

作為一種解決方法,您可以在刪除調用中添加一個主體,然后 Axios 將添加一個內容類型,這應該可以解決問題。

const handleDeleteActivityTest = () => {
    Axios.delete('https://localhost:5001/api/activities/e2beb0eb-eaaa-49ee-92d8-daf472210456', {
      data: {foo: 'bar'}
    });
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM