简体   繁体   中英

How to send a NODE.JS post request from an Angular Project?

I have a NODE.JS api using expressjs that connects to an SQL Server, and I want to use it in an angular project. I make use two files, a route file and a controllers file. My route file is as follows:

module.exports = (app) => {
    const UsrContrllr = require('../Controllers/users.controllers');

    //1. GET ALL USERS
    app.get('/api/users', UsrContrllr.func1);

    
    //2. POST NEW USER
    app.post('/api/user/new', UsrContrllr.func2);
};

And my controllers file is given below:

const mssql = require('mssql');

exports.func1 = (req, res) => 
{
    // Validate request
    console.log(`Fetching RESPONSE`);
    // create Request object
    var request = new mssql.Request();
    // query to the database and get the records
    const queryStr = `SELECT * FROM USERS`;
    request.query(queryStr, function (err, recordset) {
        if (err) console.log(err)
        else {
            if (recordset.recordset.toString() === '') {
                res.send('Oops!!! Required data not found...');
            }
            else {
                // send records as a response
                res.send(recordset);
            }
        };
    });
};

exports.func2 = (req, res) =>
{
     // Validate request
     console.log(`INSERTING RECORD ${req}`);
     // create Request object
     var request = new mssql.Request();
     // query to the database and get the records
     const queryStr = `INSERT INTO GDUSERS (USERCODE, PASSWORD, LANGUAGE, USERCLASS, FIRSTNAME, LASTNAME, CONTACTNO) VALUES ('${req.body.usercode}', '${req.body.password}', 'EN', '0', '${req.body.firstname}', '${req.body.lastname}', '${req.body.contactno}');`;
     request.query(queryStr, function (err, recordset) {
         if (err) console.log(err)
         else {
             if (recordset.recordset.toString() == '') {
                 res.send('Oops!!! Required data not found...');
             }
             else {
                 // Send records as response
                 res.send(recordset);
             }
         };
    });
};

The GET request works well, but when I try to run the POST request directly from the angular application, I get an error stating

Cannot GET URL/api/user/new

The angular code in my angular project is:

signup() {
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    console.log(this.user); //User details come from a form

    this.http.post(“URL", this.user, options)
    .subscribe( 
    (err) => {
        if(err) console.log(err);
        console.log("Success"); 
    });
  }

I'm not sure whether the angular code I'm using, is right or not, and I don't know where I'm going wrong. How does one exactly send a http POST request from an Angular project?

this i the way i handled my user signup with http.post calls. my approach is slightly different when signing up user because i am using a promise instead of observable (which i normally use for my servicecalls). but i will show you both ways.

createUser(user: User): Promise < string > {
  const promise = new Promise < string > ((resolve, reject) => {
   const userForPost = this.createUserForPost(user);
    this.http.post(environment.backendUrl + '/api/user/signup', userForPost, this.config).toPromise < HttpConfig > ()
    .then(createdUser => {
    }).catch(error => {
      console.log(error);
    });
});
 return promise; 
}

here another example with an observable

createForumPost(forumPost: ForumPost) {
 this.http.post < { message: string, forumPostId: string } > (environment.backendUrl + '/api/forumPosts', forumPost).subscribe((responseData) => {
  const id = responseData.forumPostId;
  forumPost.id = id;
 });
}

i defined my URL somewhere else and then just use the environment.backedUrl + ' path ' to define my path (the same as the path in your backend controller)

this is one of my first answers here on SO. i am sry if it is a bit messy i hope i was able to help with my examples:)

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