theTechGrandma
theTechGrandma

Reputation: 103

Express Router :id

This is my first attempt at using Angular/Nodejs/Express to get information from a SQL Server. I've tried several different implementations and the result seems to be the same. This should be easy, what am I doing wrong here? Using Postman, no matter which route I use, it returns all records. The route for /:id brings back all records as well, instead of just the one. Thanks for any help!

var express = require('express'); // Web Framework
var bodyParser = require('body-parser');
var sql = require('mssql'); // MS Sql Server client
var app = express();


app.use(bodyParser.json({
  type: 'application/json'
}));

var router = express.Router();
app.use("/api/images/", router)

//CORS Middleware
app.use(function(req, res, next) {
  //Enabling CORS 
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, contentType,Content-Type, Accept, Authorization");
  next();
});

var server = app.listen(process.env.PORT || 8080, function() {
  var port = server.address().port;
  console.log("App now running on port", port);
});

// Connection string parameters.
var dbConfig = {
  user: 'sa',
  password: '',
  server: 'localhost\\SQLEXPRESS01',
  database: 'ImageDB'
};

//Function to connect to database and execute query
var executeQuery = function(res, query, next) {
  sql.connect(dbConfig, function(err) {
    if (err) {
      console.log("Error while connecting database :- " + err);
      res.send(err);
    } else {
      // create Request object
      var request = new sql.Request();
      // query to the database
      request.query(query, function(err, rs) {
        if (err) {
          console.log("Error while querying database :- " + err);
          res.send(err);
        } else {
          res.send(rs);
        }
      });
    }
  });
}

//GET API
router.get("/:id", function(req, res) {
  var id = req.params.id;
  var query = "select * from [TestTable] where ID = " + id;
  executeQuery(res, query);
});


router.get("/", function(req, res) {
  var query = "select * from [TestTable]";
  executeQuery(res, query);
});

module.export = router;

Upvotes: 1

Views: 2579

Answers (1)

Usman Hussain
Usman Hussain

Reputation: 187

Comment out your router.get("/".... route and then hit the api and check if the router.get("/:id".. is actually hitting or not may be when ever you calls the api your router.get("/"... calls instead of router.get(":id".... route thats why you are returning back all the data. Then check it out why your :id route does not hit because :id route will never return all the data if your sql query is ok.

Upvotes: 1

Related Questions