Home > other >  Cannot GET /the route Error , in REST Postman
Cannot GET /the route Error , in REST Postman

Time:07-28

I'm trying to create a simple REST api using Postman

Created product table and inserted one row

create database mydb
use mydb
create table product(id int,name varchar(20),description varchar(20),price int)
insert into product values(1,"Bag","good",2000);

[directory of code][1]

[1]: https://i.stack.imgur.com/lZKS6.png

[db-properties.js]

module.exports={
    host:'localhost',
    user:'root',
    password:'Harini@123',
    dbName:'mydb'
}

[db-connection.js]

var dbProps=require("./db-properties");
var mysql=require("mysql");

 module.exports={getConnection:()=>{
 return mysql.createConnection({
   host:dbProps.host,
    user:dbProps.user,
    password:dbProps.password,
    database:dbProps.dbName
});
}
 }

[product.controller.js]

var dbcon=require("../config/db-connection");
var connection=dbcon.getConnection();
connection.connect();
var express=require("express");
var router=express.Router();
router.get("/",(req,res)=>{
     dbcon.query("select * from product",(error,results,fields)=>{
         if(error){
            console.error("Error while fetching data");
        }
         else{
            res.send(results);
        }
    }
    )
 })
module.exports=router;

[server.js]

var express=require("express");
var app=express();
var productAPI=require("./controller/product.controller");
app.use("api/products",productAPI);

const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});
// app.listen(8080);
// console.log("server up and running on port 8080");

After starting the server with node server

In postman if I try the GET and the url localhost:8080/api/products I get

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /api/products</pre>
</body>
</html>

What I'm doing wrong and how I can correct it? Thanks!

CodePudding user response:

In the place of

app.use("api/products",productAPI);

add a /

app.use("/api/products",productAPI);
  • Related