API 返回错误的 API 路径

问题描述

我有以下 JavaScript 代码

$(document).ready(function () {
  $("#customers .js-delete").on("click",function () {
    if (confirm("Are you sure you want to delete this customer?")) {
      $.ajax({
        url: "api/customers/" + $(this).attr("data-customer-id"),method: "DELETE",success: function () {
          console.log("Success");
        }
      });
    }
  });
});

当我运行它时,我在控制台中收到以下错误

jquery-3.5.1.js:10099 DELETE https://localhost:44367/Customers/api/customers/5 404

问题是 API 调用应该类似于 https://localhost:44367/api/customers/5

我该如何解决这个问题?

解决方法

因为它走的是相对路径。仅在网址开头添加“/”。

url: "/api/customers/" + $(this).attr("data-customer-id"),

它应该带你到 https://localhost:44367/api/customers/5 而不是 https://localhost:44367/Customers/api/customers/5