Friday, 17 March 2017

Angular 2 put method is not working with node js

Actually i need to update to database using node js update method, but i have tried lot of ways but since its not working. 

This are all i have tried..

Angular 2
-------------
 private getHeaders(){
        let headers = new Headers();
        headers.append('Accept', 'application/json');
        return headers;
    }
   updateMethod(params : any,url : string){           
          //var content = new URLSearchParams();
         // let searchParams = new URLSearchParams();
          params.url = url;
        /*  for (let param in params) {
               searchParams.set(param, params[param]);
          }*/          
          /*let apiHeaders = new Headers({  'Accept' : 'application/json','Content-Type': 'application/json',"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS" });
          apiHeaders.append('Method', 'PUT');                           
          apiHeaders.append('Content-Type', 'application/json;charset=UTF-8');
          apiHeaders.append('Access-Control-Allow-Credentials',"true");*/
          //console.log(searchParams);          
          return this.http
             .put(this.baseUrl+"api/update", JSON.stringify(params), {headers: this.getHeaders()})
             .map(res => res.json());
    }   


Nodejs 
------------

//Update Method
router.put('/api/update', function(req, res) {
    res.setHeader('Access-Control-Allow-Origin', '*');  

    var params = {};        
    for(var keyName in req.body){
        if(keyName != "url"){
            params[keyName] = req.body[keyName];    
        }
    }   
    console.log(params);

    //Update Api Call
    request.put(
        baseUrl + req.body.url,
        { json: params },
        function (error, response, body) {
            if (!error && response.statusCode == 200) {
                res.send(body);
            }else{  
                if(error == null){
                    res.send(false);    
                }else{
                    res.send(error);
                }
            }
        }
     );

}); 

Every Time I'm Getting Error Like This "XMLHttpRequest cannot load http://localhost:8081/api/update. Method PUT is not allowed by Access-Control-Allow-Methods in preflight response.".. Please give any solution..



via Vijay

No comments:

Post a Comment