【问题标题】:Converting $ajax to fetch() for PUT request为 PUT 请求将 $ajax 转换为 fetch()
【发布时间】:2018-01-26 15:46:45
【问题描述】:

我已尝试翻译以下 jquery 代码以改用 fetch 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()
})

【问题讨论】:

    标签: javascript node.js ajax express fetch-api


    【解决方案1】:

    我假设您在 Express 中使用 bodyParser,否则 jQuery 版本将无法工作。

    headers: {
        'Content-Type': 'application.json'
    },
    

    应该是

    headers: {
        'Content-Type': 'application/json'
    },
    

    【讨论】:

      猜你喜欢
      • 2020-01-12
      • 2022-11-27
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 2015-10-06
      • 2016-10-10
      相关资源
      最近更新 更多