What is the correct way to make a HTTP request from Angular to Node js API?

Issue

Im making an API call rom angular to nodejs like below>

        public TUpdation(data): Observable<any>{
          const headers = new HttpHeaders(); 
          headers.set('content-type', null);  
          headers.set('Accept', 'multipart/form-data');
          headers.set('Access-Control-Allow-Origin',"*");
          return this.http.post(API.UPDATION, data, { headers }); 
        }

In node.js portion, I’m trying to receive in the function below.

      exports.Updation = async (req,res,next) => {
          console.log("req.body : ",req.body); //Not getting the contents (empty)
          var classTM = req.body.checkbox2;
          var _entityclass;
           try{
             if(entityclass){
                _entityclass = "EE";
             }
            else if(entityclass){
                _entityclass = "TM";
             }
            else{
                _entityclass = "TMP";
             }
            try{
               console.log("req.body --- !!!  ",req.body); // Here Im able to get the contents
             }
            catch(e){
              }
           }
       catch(e){
       }
       }

My problem here is I can’t get the body contents at first. Whatever I’m trying to do, not able to get the re.body contents on top. In second try I’m able to fetch. Can anybody please help me. what I’m doing wrong?

Solution

Maybe you can try with this code below:

public TUpdation(data): Observable < any > {
    const headers = new HttpHeaders();
    // set content-type: `application/json`
    headers.set('content-type', 'application/json'); 
    // you can comment: multipart/form-data, if it's still does not work
    headers.set('Accept', 'multipart/form-data'); 
    headers.set('Access-Control-Allow-Origin', "*");
    // make sure your "data" is not an empty object
    // you can console.log(data); 
    return this.http.post(API.UPDATION, data, {
        headers
    });
}

After you change your code in your Angular app with that code above, now, make sure You’ve been add body-parser in your express app.

You can set your body-parser with this code below:

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

You can copy that code above and put in your app.js or server.js.

I hope it can help you.

Answered By – Titus Sutio Fanpula

Answer Checked By – Mary Flores (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.