将 $ajax 转换为 PUT 请求的 fetch()
Converting $ajax to fetch() for PUT request
我尝试将以下 jquery 代码翻译为使用提取 API。它发出 PUT
请求:
function save () {
$.ajax('/{{user.username}}', {
method: 'PUT',
data: {
street: $('#street').val(),
city: $('#city').val(),
state: $('#state').val(),
zip: $('#zip').val()
},
complete: function () {
cancel()
location.reload()
}
})
}
这是提取 API 请求:
fetch('/{{user.username}}', {
method: 'PUT',
headers: {
'Content-Type': 'application.json'
},
body: JSON.stringify({
street: document.getElementById("street").value,
city: document.getElementById("city").value,
state: document.getElementById("state").value,
zip: document.getElementById("zip").value
})
}).then(() => {
cancel()
location.reload()
})
}
当我 console.log
使用 Node 将它发送到终端时,我得到一个空数组。
我正在尝试使用以下方式在 Express 中处理它:
app.put('/:username', function (req, res) {
console.log(req.body)
console.log("hello")
var username = req.params.username
var user = getUser(username)
user.location = req.body
saveUser(username, user)
res.end()
})
我假设您在 Express 中使用 bodyParser,否则 jQuery 版本将无法工作。
headers: {
'Content-Type': 'application.json'
},
应该是
headers: {
'Content-Type': 'application/json'
},
我尝试将以下 jquery 代码翻译为使用提取 API。它发出 PUT
请求:
function save () {
$.ajax('/{{user.username}}', {
method: 'PUT',
data: {
street: $('#street').val(),
city: $('#city').val(),
state: $('#state').val(),
zip: $('#zip').val()
},
complete: function () {
cancel()
location.reload()
}
})
}
这是提取 API 请求:
fetch('/{{user.username}}', {
method: 'PUT',
headers: {
'Content-Type': 'application.json'
},
body: JSON.stringify({
street: document.getElementById("street").value,
city: document.getElementById("city").value,
state: document.getElementById("state").value,
zip: document.getElementById("zip").value
})
}).then(() => {
cancel()
location.reload()
})
}
当我 console.log
使用 Node 将它发送到终端时,我得到一个空数组。
我正在尝试使用以下方式在 Express 中处理它:
app.put('/:username', function (req, res) {
console.log(req.body)
console.log("hello")
var username = req.params.username
var user = getUser(username)
user.location = req.body
saveUser(username, user)
res.end()
})
我假设您在 Express 中使用 bodyParser,否则 jQuery 版本将无法工作。
headers: {
'Content-Type': 'application.json'
},
应该是
headers: {
'Content-Type': 'application/json'
},