0

I want to create a simple RESTful service for managing the list of genres of movies. First I tried to handle all the HTTP requests to a given route('/api/genres') in a single file (server.js), and my code worked, i.e I was able to Post movies, update movies when I handled the routes from the main server.js file. But then, I tried to handle the routes in a separate file, but I'm getting problems.

Problems:

  1. It seems my movies variable from server.js has not been able to export itself, as, I'm getting 'undefined' on console.log(movies) in generes.js. So for post and put request, nothing is being displayed

  2. I have read that router.get and app.get are not much different, still, app.get doesn't work in genres.js

    Server.js

const app = express();
const generes = require("./routes/api/genres");
app.use(express.json());
var movies = [
  {
    name: "harry potter",
    genere: "fiction"
  },
  {
    name: "IT",
    genere: "horror"
  },
  {
    name: "chicchore",
    genere: "comedy"
  },
  {
    name: "A walk to remember",
    genere: "romantic"
  }
];

app.use("/api/genres", generes);
const port = process.env.PORT || 3000;
app.listen(port, () => console.log("Server running..."));
module.exports.movies = movies;

genres.js

var express = require("express"),
app = express();
const server = require("../../server");
const router = express.Router();

app.use(express.json());

//importing movies array
var movies = server.movies;

router.get("/", (req, res) => {
  res.send(movies);
});

router.post("/", (req, res) => {
  var movie_obj = {
    name: req.body.name,
    genere: req.body.genere
  };
  movies.push(movie_obj);
  res.send(movie_obj);
});

router.put("/:id", (req, res) => {
  var flag = 0;
  movies.forEach(ele => {
    if (ele.name == req.params.id) {
      ele.name = req.body.name;
      flag = 1;
      res.send(movies);
    }
  });
  //if (flag == 0) res.send(`no such movie exists ${req.params.id}`);
});
module.exports = router;
function newFunction() {
  return "movies";
}

the directory structure of my project

Also,When I used app.get instead of router.get. I got the following error: error

anonymous
  • 21
  • 1
  • 5
  • I donot know why movies is not correctly exported to genres.js. But there is circular reference happening with your imports, i.e. You are importing genres.js to server.js and again importing server.js into genres.js, which have to be avoided. Instead move movies declaration( or whatever the data source is) to genres.js. You can also look into express js app wide globals like app.set and app.get if that is what you need – Jay Surya Sep 19 '19 at 17:58
  • Also, look at these workarounds https://stackoverflow.com/questions/10869276/how-to-deal-with-cyclic-dependencies-in-node-js – Jay Surya Sep 19 '19 at 18:01

0 Answers0