【问题标题】:Trying to patch array on rest api尝试在rest api上修补数组
【发布时间】:2017-07-19 11:33:15
【问题描述】:

我无法成功地将值推送到作为 rest api 上的对象的一部分的数组。我正在关注这个Patching arrays,但我无法让它工作。

const xhr = new XMLHttpRequest();

const formData = { "op": "add", "path": "/residents", "value": this.state.person.id };
console.log(formData)

xhr.open('PATCH', 'http://localhost:3008/planets/' + this.state.person.planetID);

xhr.setRequestHeader('Content-type', 'application/json');

xhr.responseType = 'json';

xhr.addEventListener('load', () => { 

    //patch the person const planet id 

});
xhr.send(formData);

【问题讨论】:

  • 你的后端是否理解 JSON Patch,如果是,你得到的错误信息是什么?
  • 是的。这是我得到的而不是推送到数组并且没有错误:{“edited”:“2014-12-20T20:58:18.421Z”,“气候”:“温带,热带”,“surface_water”:“8” ,“名称”:“Yavin IV”,“直径”:“10200”,“rotation_period”:“24”,“创建”:“2014-12-10T11:37:19.144Z”,“地形”:“丛林,雨林”、“重力”:“1 标准”、“轨道周期”:“4818”、“人口”:“1000”、“id”:3、“居民”:[]、“电影”:[1]、“ [object 对象]": "" },

标签: javascript rest xmlhttprequest


【解决方案1】:

RFC Doc for json 补丁中所述,您需要在路径中附加一个“-”:

const formData = { "op": "add", "path": "/residents/-", "value": this.state.person.id };

或指定一个显式索引,您希望将值添加到数组中。

【讨论】:

  • 不会推送到数组。 {“已编辑”:“2014-12-20T20:58:18.423Z”,“气候”:“冷冻”,“surface_water”:“100”,“名称”:“霍斯”,“直径”:“7200”, “rotation_period”:“23”、“created”:“2014-12-10T11:39:13.934Z”、“terrain”:“苔原、冰洞、山脉”、“gravity”:“1.1 标准”、“orbital_period “:“549”,“人口”:“未知”,“id”:4,“居民”:[],“电影”:[2],“[object Object]”:“”}
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多