简体   繁体   English

Javascript 获取 API PUT 请求

[英]Javascript Fetch API PUT Request

I want to update the book ratings.我想更新图书评分。 User will submit rating for a particular book through a form.用户将通过表单提交对特定书籍的评分。 postRatings is an action creator which is dispatched to component with the form. postRatings是一个动作创建者,它通过表单发送到组件。 Books variable contains the same book object as present in the json file. Books变量包含与 json 文件中相同的书 object。 The rating gets updated for the specific book in the Books variable and then I want to delete the older object and put this updated object. Books变量中特定书籍的评级得到更新,然后我想删除旧的 object 并将这个更新的 object 放入。 But when I try to do this, I get 404: Not Found error message.但是当我尝试这样做时,我得到404: Not Found错误消息。 It would be great if someone can point out where am I mistaking and help me solve this error.如果有人能指出我错在哪里并帮助我解决这个错误,那就太好了。

JSON File (Fake Rest API made using json-server Node Module): 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: 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);
  });
}

You have to include the id of the object that you want to update.您必须包含要更新的 object 的 ID。 see the default route of json-server查看json-server的默认路由

so in your fetch url, add the book id at the end of the route因此,在您获取 url 时,在路线末尾添加图书 ID

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

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

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