簡體   English   中英

將$ ajax轉換為fetch()以進行PUT請求

[英]Converting $ajax to fetch() for PUT request

我試圖翻譯以下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()
})
}

當我用node將console.log到終端時,我得到一個空數組。

我正在嘗試使用以下方法在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'
},

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM