【问题标题】:Update with axios put do not work on API / React.js使用 axios put 更新不适用于 API / React.js
【发布时间】:2021-05-28 06:27:53
【问题描述】:

我是刚开始反应和休息Apis的新手,但希望我能得到关于这个的提示或提示..

我试图在 ASP.Net Core 中对我自己的 API buildt 执行更新功能,但我收到“PUT http://localhost:33255/api/Cities/9 400 (Bad Request)”错误...我认为我的 ID 没有通过?

我试图发送的值

state = {
  Cities: [],
    editCitiesData: {
    citiesId: '',
    cityName: '',
    cipCode: '',
    countryName: ''
  },
  editCitiesModal: false
}

我的功能:

updateCities(){

  let {cityName, zipCode, countryName } = this.state.editCitiesData;


  axios.put('http://localhost:33255/api/Cities/' + this.state.editCitiesData.citiesId, {
    cityName, zipCode, countryName
  }).then((response) => {
    this._refreshCities();
    console.log(response.data);
  })
}

还有我的 onClick:

<Button color="primary" onClick={this.updateCities.bind(this)}>Update city</Button>{' '}

感谢您的帮助!

编辑 ////

我的 api 上的断点显示: Return 0

【问题讨论】:

  • 您的this.state.editCitiesData.citiesId 是空字符串吗?就像你在状态中定义的那样。尝试首先手动添加一个 id 到您的状态,这样您就可以研究前端或后端是否有任何问题。也推荐使用 Postman,看看这个:postman.com
  • 是的,它是一个空字符串。我检查了请求在我的 Api 中的样子,并用图片更新了我的问题。当我使用邮递员时,我可以成功更新,但我得到这个状态:204 没有内容。我的 api 是否因 put 方法而损坏?
  • PUT 动词表示您将替换行信息。前端获取 id 是否在您的数据库中?似乎您正在尝试放置不存在的东西!
  • 是的。当我查看标头时,我的 id 未显示在请求有效负载中...如何在函数中正确发送 id?感觉我什么都试过了。我现在也得到这个“PUT localhost:33255/api/Cities/405 (Method Not Allowed)”..

标签: javascript reactjs axios asp.net-core-webapi rest


【解决方案1】:

你需要给按钮一个值,所以当你调用 updateCities 函数时,传递和接收来做查询:

<Button value={city.id} color="primary" onClick={this.updateCities.bind(this)}>Update city</Button> 

现在,在 updateCities 函数中接收 id:

updateCities({currentTarget}){
  const id = currentTarget.value //here you define the id of the city to update

  let {cityName, zipCode, countryName } = this.state.editCitiesData;


  axios.put('http://localhost:33255/api/Cities/' + id, { //here you pass that id
    cityName, zipCode, countryName
  }).then((response) => {
    this._refreshCities();
    console.log(response.data);
  })
}

【讨论】:

  • 我理解但现在得到这个“TypeError: Cannot read property 'value' of undefined”?
  • 如果未定义,则表示您还没有该值。我认为您需要先获取城市的 id,然后才能将其传递给函数。否则你做事不正确。第一件事。使用 componentDidMount() 调用以获取所有城市,并将响应设置为数组状态 (Cities)。然后使用 map 遍历所有城市,并用一个包含您需要传递给函数的 id 的按钮来渲染每个城市,这样您最终可以调用该函数来更新数据库中的数据。希望这有助于解决问题。
猜你喜欢
  • 1970-01-01
  • 2019-01-26
  • 1970-01-01
  • 2019-04-25
  • 2021-03-25
  • 2019-04-11
  • 2020-07-21
  • 1970-01-01
  • 2019-04-27
相关资源
最近更新 更多