首页 > 解决方案 > Axios Put 不更新 Value

问题描述

我正在尝试使用带有 Axios 的 PUT 请求来更新未按预期工作的记录。我有以下 JSON 数组:

[
  {
    "Name": "Simagdo"
  }
]

我这样使用:

let jsonInput = {
"content": JSON.stringify(jsonArray)
}

有了这个,我发送了 PUT 请求:

export const putItem = (url, content) => {
    return axios.put(url, content, {
        headers: {
            'Content-Type': 'application/json'
        }
    }).then(response => {
        console.log(`Status: ${response.status}`)
        console.log(`Data: ${response.data}`)
        return response;
    });
}

我在这里调用方法:

let updateLayout = {
    "content": JSON.stringify(jsonInput)
}

console.log(updateLayout)

putItem('http://localhost:8080/api/v1/saveFile/1', updateLayout)
    .then(response => {
        console.log(response);
    })
    .catch(error => {
        console.log(error)
    })

当我尝试这个时,页面刷新但是当我查看我发送请求的后端时,PUT 请求没有改变值。当使用 Postman 尝试使用类似 JSON 字符串的 PUT 请求时,一切正常。

这是发送 PUT 请求后 Chrome 的 cURL 输出:

curl 'http://localhost:8080/api/v1/saveFile/1' \
  -X 'PUT' \
  -H 'Connection: keep-alive' \
  -H 'sec-ch-ua: "Google Chrome";v="93", " Not;A Brand";v="99", "Chromium";v="93"' \
  -H 'Accept: application/json, text/plain, */*' \
  -H 'Content-Type: application/json' \
  -H 'sec-ch-ua-mobile: ?0' \
  -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36' \
  -H 'sec-ch-ua-platform: "Windows"' \
  -H 'Origin: http://localhost:3000' \
  -H 'Sec-Fetch-Site: same-site' \
  -H 'Sec-Fetch-Mode: cors' \
  -H 'Sec-Fetch-Dest: empty' \
  -H 'Referer: http://localhost:3000/' \
  -H 'Accept-Language: de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7' \
  --data-raw '{"content":"[{\"Name\":\"Simagdo\"}]"}' \
  --compressed

标签: javascriptjsonaxios

解决方案


我自己找到了我的问题的解决方案。如果其他人有这样的问题,这就是缺少的:

在事件方法中,我忘记调用方法preventDefault();

这就是我现在拥有的:

let updateLayout = {
    "content": JSON.stringify(jsonInput)
}

console.log(updateLayout)

event.preventDefault();

putItem('http://localhost:8080/api/v1/saveFile/1', updateLayout)
    .then(response => {
        console.log(response);
    })
    .catch(error => {
        console.log(error)
    })

推荐阅读