【问题标题】:Javascript Fetch API PUT RequestJavascript Fetch API PUT 请求
【发布时间】:2020-12-19 07:36:40
【问题描述】:

我想更新图书评分。用户将通过表单提交对特定书籍的评分。 postRatings 是一个动作创建者,它通过表单发送到组件。 书籍变量 包含与 json 文件中相同的书籍对象。 Books 变量中特定书籍的评分会更新,然后我想删除较旧的对象并放置这个更新的对象。但是当我尝试这样做时,我收到 404: Not Found 错误消息。如果有人能指出我错在哪里并帮助我解决这个错误,那就太好了。

JSON 文件(使用 json-server 节点模块制作的假 Rest API):

{
  "books": [
    {
      "id": "0",
      "title": "1984",
      "author": "George Orwell",
      "rating": "4.6",
      "points: "228",
      "total": "50
    },
    {
      "id": "1",
      "title": "To Kill a Mockingbird",
      "author": "Harper Lee",
      "rating": "4.8",
      "points: "241",
      "total": "50
    }
  ]
}

postRatings Action Creator:

export const postRatings = (Books, title, rating) => (dispatch) => {  
  Books.some(function(obj){
    if(obj.title==title) {
      obj.total = parseInt(obj.total)+1;
        let newPts = parseInt(obj.points) + parseInt(rating);
        obj.points = ""+newPts;
        let newRating = (parseInt(obj.points) + parseInt(rating)) / parseFloat(obj.total);
        obj.ratings = ""+Math.floor(newRating * Math.pow(10, 1)) / Math.pow(10, 1).toFixed(1);
        return true;
    }   
  });
  fetch('localhost:3001/books', {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(Books)
  })
  .then(response => {
    if(response.ok) {
      return response;
    } else {
        var error = new Error('Error- ' + response.status + ":" + response.statusText);
        error.response = response;
        throw error;
    }
  },
  error => {
    var errmess = new Error(error.message);
    throw errmess;
  })
  .then(response => response.json())
  .then(response => {console.log("response:"+JSON.stringify(response)); alert("Rating Added!")})
  .catch(error => {console.log('Error Message: '+ error.message)
    alert("Some Problem Occurred.\nError: "+error.message);
  });
}

【问题讨论】:

    标签: javascript json reactjs react-redux fetch


    【解决方案1】:

    您必须包含要更新的对象的 ID。见default route of json-server

    所以在你的 fetch url 中,在路由的末尾添加 book id

    fetch(`localhost:3001/books/${Books.id}`)
    

    【讨论】:

    • 啊!这解决了这个问题。我试图更新整个书对象而不是特定的书。我也错过了 PUT 的复数路线。感谢您帮助我:-)
    • @KevalDhanani 不客气。很高兴我能帮忙
    猜你喜欢
    • 2020-01-12
    • 2017-01-28
    • 2017-02-19
    • 2016-11-28
    • 2018-01-26
    • 1970-01-01
    • 2021-07-18
    • 2020-11-11
    • 2018-01-07
    相关资源
    最近更新 更多