Bigya Tuladhar
Bigya Tuladhar

Reputation: 69

Node js REST not working using express server

I am new to node, I am trying to use REST api but it's not working. Below is the code I am working with:

app.js


 

    import express from "express";
     import cors from "cors";
     import dotenv from "dotenv";
     import conn from "./conn.js";
     import users from "./routes/users.route.js";
    
    dotenv.config();
    
    const app = express();
    
    app.use(express.json());
    app.use(cors);
    
    const port = process.env.PORT || 8000;
    
    //using this to check if app.get() was working or not.
    app.get("/", (req, res) => {
      res.send("Getting some data");
    });
    
    app.use("/api/users", users);
    
    app.use("*", (req, res) => {
      res.status(400).json({ error: "Invalid Request URL" });
    });
    
    if (conn) {
      app.listen(port, () => {
        console.log(`Server is running on port: ${port}`);
      });
    }


conn.js



    import mysql from "mysql";
    
    const conn = mysql
      .createPool({
        host: "localhost",
        user: "root",
        password: "",
        database: "cruddatabase",
      });
    
    export default conn;

users.route.js



    import express from "express";
    import userController from "../controller/user.controller.js";
    
    const router = express();
    
    router.route("/").get(userController.getUpayaUser);
    
    export default router;

user.controller.js



    export default class userController {
      static async getUpayaUser(req, res, next) {
        console.log("here");
        res.json("User Controller");
      }
    }

Here I am not doing anything complex but I just want to console some stuff to see if it's working and then move on to doing something more. When running nodemon app.js, I do get the log saying "Server is running on port 5000"; But after this nothing. I am using postman to check the responses, and it shows a message "could not get a response". On further testing I found that the reqesut is stuck on pending. the app.get('/') was working but it took 10 mins + to return a simple text.

Upvotes: 1

Views: 51

Answers (1)

Sachin Ananthakumar
Sachin Ananthakumar

Reputation: 810

change app.use(cors) to app.use(cors())

Upvotes: 2

Related Questions