简体   繁体   中英

Post request works but Put request doesn't in angular 2

I make a PUT request to a Rest API in angular 2 but it's not working. When I make the same request with POST, it works fine.

This is my view :

save(){
  this.params['user_id']=this.user_id;
  this.params['video_id']=this.video_id;
  this._dashboardService.update('uservalues',this.params)
    .subscribe(x=> {
      console.log('test');
    });
}

My view calls my service :

update(data ,param?) {
  let authToken = localStorage.getItem('auth_token');
  var myObject = Object.assign({'auth_token':authToken}, param);
  let params={};
  for (var name in myObject) {
    params[name]=myObject[name];
  }

  let body=JSON.stringify(params);
  let headers = new Headers({ 'Content-Type': 'application/json' });
  return this._http
    .put(this._url+'test', body, headers)
    .map(res=> res.json());
}

My console :

OPTIONS http://host.com/dev/api/test 406 (Not Acceptable)
XMLHttpRequest cannot load http://host.com/dev/api/test. Response for preflight
has invalid HTTP status code 406

My headers (API) :

    header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Request-Headers: Accept, Authorization");
header("Access-Control-Expose-Headers: Authorization");
header("Access-Control-Allow-Headers:X-Requested-With, Accept, Authorization");

When i comment this code in my API my PUT request works

private function set_headers(){
            // header("HTTP/1.1 ".$this->_code." ".$this->get_status_message());
            header("Content-Type:".$this->_content_type);
        } 

Any ideas ?

use id of the record like " http://host.com/dev/api/test "+id(record id of the record) as mentioed in the API help PUT api/test/{id}

update(data ,param?) {
  let authToken = localStorage.getItem('auth_token');
  var myObject = Object.assign({'auth_token':authToken}, param);
  let params={};
  for (var name in myObject) {
    params[name]=myObject[name];
  }

  let body=JSON.stringify(params);
  let headers = new Headers({ 'Content-Type': 'application/json' });
  return this._http
    .put(this._url+'test'+id, body, headers) //*use id here*
    .map(res=> res.json());
}

If you have created Web API for IIS then check if you have CORS handler and, also check if you have this in your Web.config:

<system.webServer>
  <modules>
    <remove name="WebDAVModule" />
  </modules>
  <handlers>
    <remove name="WebDAV" />
  </handlers>
</system.webServer>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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