Piotr Kaliński Piotr Kaliński - 25 days ago 6
JSON Question

Angular2 how to correct put request

Ok then, I have a single problem, the

Request URL:http://.../rest/1.0/brand/test145
Request Method:PUT
Status Code:500 Internal Server Error
Remote Address:...

Request payload is ok
{
"name": "test145"
}

addBrand(name : string){
let body = JSON.stringify(name)
let url = this.baseUrl + '/brand/' + name;
return this.http.put(url, { name } ).
map(res => res.json());
}

addBrand(name:any){
if(!name){return;}
this.BrandService.addBrand(name)
.subscribe(
name => this.name.push(name),
error => this.errorMesage = <any>error);

}


But the put should look like http://.../rest/1.0/brand/ and then, should be only request payload. When I remove that "name" from, it doesn't load the payload.

Answer

stricly PUT is update, so the url should be in format:

http://.../rest/1.0/brand/test145 where the last part is unique id (you need to indicate what you mean to update)

If you expect to create a record, you should rather POST to http://.../rest/1.0/brand

But you can always choose to deviate from conventions. In order to PUT to .../brand with a payload { "name": "test145" } you would need to:

addBrand(name : string){
    let body = JSON.stringify({ name: name })
    let url = this.baseUrl + '/brand'
    return this.http.put(url, body ).
    map(res => res.json());
}