Fairly new to web development, so it’s quite likely that this is a simple mistake on my part, but I’ve tried figuring this out for the past hour and I’ve got nothing.
Here’s my current code, after I’ve stripped it down to the bare minimum, still not working.
app.js:
const express = require('express');
const cors = require('cors');
require('dotenv').config();
const port = process.env.PORT || 3000;
const apiPath = process.env.API_PATH || '/api/v1';
const gamesRoute = require('./routes/gamesRoute');
const app = express();
app.use(cors());
app.use(express.json());
app.use(`${apiPath}/games`, gamesRoute);
// Start server, binding it to specified port
app.listen(port, function() {
// Log a message when server is successfully started
console.log(`Server is running on port ${port}`);
});
app.get('/', function(req, res) {
res.send("test");
});
gamesRoute.js:
const express = require('express');
const router = express.Router();
router.get('/', async function(req, res) {
console.log("test");
res.json({ msg: "test" });
});
module.exports = router;
Response (I’m using the VSCode extensions ‘humao.rest-client’, and calling GET localhost:3000/api/v1/games
):
HTTP/1.1 404 Not Found
X-Powered-By: Express
Access-Control-Allow-Origin: *
Content-Security-Policy: default-src 'none'
X-Content-Type-Options: nosniff
Content-Type: text/html; charset=utf-8
Content-Length: 151
Date: Wed, 10 Jan 2024 11:46:35 GMT
Connection: close
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /api/v1/games</pre>
</body>
</html>
I also get nothing in the console.
My assumption is that I’m making a very basic mistake, but I have no idea what it is.
I’ve tried looking at tutorials, both on youtube, the express documentation, and random posts. Based on what I’ve found, I’m doing things correctly, so I’m in a bit of a stump. I’ve also looked through a bit more than half of the questions stack overflow recommended that might be duplicates, and none of them seem to solve my issue, unless I’m just too dumb to get it.
2
Answers
My issue was indeed simple and stupid. The environment variable I used was overriding '/api/v1', and in the .env file I had only put 'api/v1' without the first '/'.
if you want use router.use(‘/’) in gamesRoute file than const router = express.Router() is valid but you need to use routes than you will use here same as atteched code.
gamesRoute.js: