如何使用 jQuery / Axios 执行 PUT 请求?它总是返回错误 400

时间:2021-07-01 06:54:09

标签: javascript jquery ajax axios put

首先,我如何在 JavaScript 中执行 PUT 请求? (就上下文而言,我正在开发一个 Vue 应用程序) 在邮递员或任何其他客户端中的相同请求都可以完美运行,我发现问题在于 Api 期望正文为 "Content-Type": "application/x-www-form-urlencoded" 但通过 Javascript 发送它只是以纯 JSON 或不以可理解的格式发送API。

我试过:$.put("...") 但它返回未找到的函数。 我尝试使用 type / _method = "put" 进行基本的 Ajax 调用,但它也不起作用,因为发送的内容不匹配。

API 期望什么?

person: {info: {name: "--", surname: "---"}}
location: {info: {city: "--", postalc: "---"}}
ref: 1234

我如何发送?

JSON.stringify({
person: {info: {name: "--", surname: "---"}}
location: {info: {city: "--", postalc: "---"}}
ref: 1234
})

$.param(({
person: {info: {name: "--", surname: "---"}}
location: {info: {city: "--", postalc: "---"}}
ref: 1234
})

使用 Axios 请求示例:

const res = axios.put(
              "http://" + api + "/sendClientInfo/",
              {
                $.param(({
                person: {info: {name: "--", surname: "---"}}
                location: {info: {city: "--", postalc: "---"}}
                ref: 1234
                }),
              },
              {
                headers: {
                  "Content-Type": "application/x-www-form-urlencoded",
                },
              }
            );

jQuery 示例

$.ajax("http://" + api + "/sendClientInfo/", {
              type: "PUT",
              data: JSON.stringify(data),
              contentType: "application/json",
              success: function () {
                console.log("exit");
              },

1 个答案:

答案 0 :(得分:0)

<块引用>

API 期望什么?

person: {info: {name: "--", surname: "---"}}
location: {info: {city: "--", postalc: "---"}}
ref: 1234

对我来说,这看起来 API 需要 3 个 application/x-www-form-urlencoded 参数,其中前两个参数包含 JSON 值。

为了实现这一点,你需要这样的东西

const person = { info: { name: "--", surname: "---" } }
const location = { info: { name: "--", surname: "---" } }
const data = {
  person: JSON.stringify(person), // encode these values as JSON
  location: JSON.stringify(location),
  ref: 1234
}

const url = `http://${api}/sendClientInfo/`

// jQuery
$.ajax({
  url,
  method: "PUT",
  data
})

// Axios
axios.put(url, new URLSearchParams(data))

jQuery 的默认数据负载格式是 application/x-www-form-urlencoded。对象通过 $.param() method 进行编码。

如果提供 application/x-www-form-urlencoded 数据实例,Axios 也将使用 URLSearchParams。这与 $.param()

的作用相同

两个有效载荷都将被编码为

person=%7B%22info%22%3A%7B%22name%22%3A%22--%22%2C%22surname%22%3A%22---%22%7D%7D&location=%7B%22info%22%3A%7B%22city%22%3A%22--%22%2C%22postalc%22%3A%22---%22%7D%7D&ref=1234