Node.js POST Request through Angular application returns Error 404 “not found"

Viewed 1113

I am making an API using Node.js that connects to an SQL Server database. My GET requests work well, but my POST request gives me errors. I have divided my node project into two files, a routes file and a controllers file.

The code in my routes file is as follows:

module.exports = (app) => {
  const UsrContrllr = require('../Controllers/users.controllers');
  
  //1. GET ALL USERS
  app.get('/api/users', UsrContrllr.getAllUsers);

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

And the code in my controllers file is given below:

const mssql = require('mssql');

exports.getAllUsers = (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.addNewUser = (req, res) =>
{
     // Validate request
     console.log(`INSERTING RECORD ${req.body}`);
     // create Request object
     var request = new mssql.Request();
     // query to the database and get the records
     const queryStr = `INSERT INTO USERS (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}');`;
     console.log(queryStr);
     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);
             }
         };
    });
};

When I run the POST request from my angular application, I get an HttpErrorResponse, Error 404 not found.

error: “Error: Cannot POST /api/users/new" message: "Http failure response for http://url:port/api/users/new: 404 Not Found" name: "HttpErrorResponse" ok: false status: 404 statusText: "Not Found” url: "http://url:port/api/users/new”

The angular code in the service file is as follows:

private url = 'http://url:port/api/users';
signup(fName: string, lName: string, usrCode: string, pwd: string, cntctNbr: string) {
  const headers = new HttpHeaders().set('Content-Type', 'application/json');  
  const newUsr = {
    usercode: usrCode,
    password: pwd,
    firstname: fName,
    lastname: lName,
    contactno: cntctNbr
  }
  
  this.http.post(this.url + '/new', JSON.stringify(newUsr), { headers: headers }).subscribe(data => {
      console.log(data);
  });
}

I don’t understand why I am unable to add in new users. I’ve been told my code appears fine, but I don’t see any results. Where am I going wrong?

1 Answers

You are receiving a 404 (Not found) error because your POST route is defined as /user/new but in your angular app you are calling http://url:port/api/users/new

Correct the code to the following in your API:

app.post('/api/users/new', UsrContrllr.addNewUser);
Related