繁体   English   中英

Javascript 获取 API PUT 请求

[英]Javascript Fetch API PUT Request

我想更新图书评分。 用户将通过表单提交对特定书籍的评分。 postRatings是一个动作创建者,它通过表单发送到组件。 Books变量包含与 json 文件中相同的书 object。 Books变量中特定书籍的评级得到更新,然后我想删除旧的 object 并将这个更新的 object 放入。 但是当我尝试这样做时,我得到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 动作创建者:

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);
  });
}

您必须包含要更新的 object 的 ID。 查看json-server的默认路由

因此,在您获取 url 时,在路线末尾添加图书 ID

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM