【问题标题】:405 Method Not Allowed Error in AJAX POSTAJAX POST 中的 405 Method Not Allowed 错误
【发布时间】:2020-01-14 13:34:53
【问题描述】:

我正在尝试通过 Ajax POST 保存一些用户输入,但我一直遇到此错误

405 方法不允许。

var formData = {
  category: $("#category").val(),
  assetType: $("#assetType").val(),
  description: $("#description").val(),
}
console.log(formData);

$.ajax({
  dataType: 'json',
  url: '/add-asset',
  data: formData,
  type: "POST",
  enctype: 'multipart/form-data',
  processData: false,
  contentType: false,
  success: function(data) {
    if (data.status == 1) {
      openAlertDialog("Success", data.message, "Continue");
    } else {
      openAlertDialog("Error", data.message, "Continue", "");
    }
  },
  error: function(data) {
    openAlertDialog("Error", data.message, "Continue", "");
  },
});

控制器代码:

@RequestMapping(value="/add-asset", method = RequestMethod.POST)
public @ResponseBody String addAsset(@ModelAttribute AssetCategory as, Principal principal) {
    as.setAssetID(UUID.randomUUID().toString());
    as.setCreatedBy(principal.getName());

    JsonObject result = new JsonObject();

        assetService.save(as);
        result.addProperty("result", "Success");
        result.addProperty("status", 1);
        result.addProperty("message", "Changes Saved.");

    return result.toString();
}

我可以检索用户输入,但不能将其传递给我的控制器。

Chrome 中的内部源代码

【问题讨论】:

  • 这不是 AJAX 请求,因为它调用了/add-asset,但错误来自/manage-assets。我假设您在使用 GET 请求提交 form 时发出 AJAX 请求,但您并没有阻止该表单提交。
  • 我有一个 /manage-assets 的 GET 请求。我用它来填充我的数据表。在 manage-assets.html 里面有一个表单,我用来添加一些资产。所以填充数据表的 GET 请求阻止了表单提交?
  • 可能,但鉴于问题中的信息很难明确地说。在任何情况下,问题都是因为您发送的请求与服务器对该端点所期望的 HTTP 请求动词不同
  • 您如何称呼您的添加资产 POST?通过按钮点击?确保按钮是 <button type='button'> 并从点击处理程序返回 false(确定)。
  • 编辑:我使用 add-asset 作为 URL 再次运行了代码,但它仍然给出 405。我正在使用一个按钮并通过 onclick 调用它。

标签: jquery ajax spring-mvc


【解决方案1】:

我已通过将此代码放入我的表单中来修复它

<input type="hidden" name="_csrf" th:value="${_csrf.token}" />

它似乎在寻找一个令牌,所以我在我的表单中放置了一个隐藏的输入。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    • 2022-09-23
    • 2015-07-01
    • 2017-06-14
    • 2021-12-22
    • 2021-01-21
    相关资源
    最近更新 更多