For some reason my express router is not processing requests correctly. My router module is in the same directory as the app entry point. The app is located in index.js:
const express = require('express')
const app = express()
// loading router
const mainRouter = require('./mainRoutes.js')
// mounting router
app.use('/', mainRouter)
app.listen(3000)
console.log('Express server running on port 3000')
The router module is located in mainRoutes.js:
const path = require('path')
const express = require('express')
const mainRouter = express.Router()
mainRouter.get('/', function (req, res) {
res.send('Hello World, I\'m Node.js')
})
mainRouter.get('/about', function (req, res) {
res.sendFile(path.join(__dirname, 'views', 'about.html'))
})
module.exports = mainRouter
When I launch the server locally with live-server and make the following example request in chrome browser:
http://127.0.0.1:8080/about
I get the following error response:
Cannot GET /about
Does anyone have any idea as to what the issue is?
The server is listening on port 3000: app.listen(3000)
But you're trying to access it from port 8080: http://127.0.0.1:8080/about
Try http://127.0.0.1:3000/about
Related
I am trying to create a route to my users file as well as others but when I use postman to send a get request to https://localhost:3000/api/users I get a "Cannot GET api/users/ error.
I have tried putting the require statement into a variable and then passing it to the app.use() function. I also made sure the in my users.js file that the first parameter is only a "/". Also it is not just the users route it is all of my routes that do not work. Can someone see my mistake?
Here is the server.js file
const express = require("express");
const connectDB = require("./config/db");
const app = express();
//Connect DB
connectDB();
app.get("/", (req, res) => res.send("API Running"));
//define routes
const userRoute = require("./routes/api/users");
app.use("api/users", userRoute);
app.use("api/auth", require("./routes/api/auth"));
app.use("api/profile",
require("./routes/api/profile"));
app.use("api/posts", require("./routes/api/posts"));
const PORT = process.env.PORT || 3000;
app.listen(PORT, () =>
console.log(`Server started on port: ${PORT}
`)
);
And here is the users.js file, all of the other router files are similar just with different names.
const express = require("express");
const router = express.Router();
// #route get api/users
// #desc test route
// # access Public
router.get("/", (req, res) => res.send("User Route"));
module.exports = router;
I also tried changing the last line in users.js to export default router but that just resulted in an unexpected token error. Thank you in advance for the help.
Add '/' before your route definitions in the server.js file. So your route definition for the users will be app.use("/api/users", userRoute). Do the same for all your route definitions
Just replace your line app.use("api/users", userRoute); to app.use("/api/users", userRoute); in server.js
I have two questions:
Can I use cors() once in my server.js instead of calling and use it in all my router files?
Can I require express once in my server.js instead of calling it in all my router files?
My server.js now has no problems to handle CORS like below but the app also handles the users router.
server.js handles requests to /
const cors = require('cors');
const express = require('express');
const users = require('./routers/users');
const app = express();
app.use(cors());
app.use('/api/v1/user', users); // Register the user router
routers/users.js handles requests to /users
const cors = require('cors'); // Required again
const express = require('express'); // Required again
const router = express.Router();
router.use(cors());
If I don't use router.use(cors()) I will receive an CORS on the browser when I access /api/v1/users
Yes you need to use cors() only once for entire application.
No you need to require express in each file if you are segregating your routes in separate files
Folder structure:
+ index.js
+ routers
+ users.js
+ server.js
+ controllers
+ user_controller.js
How your index.js file should look like:
const cors = require('cors');
const express = require('express');
const serverRoutes = require('./routers/server');
const app = express();
// Allow cross origin access.
app.use(cors());
app.use('/', serverRoutes);
How your server.js file should look like:
const router = require('express').Router();
const userRoutes = require('./users');
router.use('/api/v1/user', userRoutes); // Register the user router
module.exports = router;
How your user.js file should look like:
const router = require('express').Router();
const userController = require('../controllers/user_controller');
router.get('/', (req, res) => {
userController.list(req, res); // or whatever your code is.
});
module.exports = router;
I am trying to import route logic from another file. In express js this is achievable via express.Route(), when i tried polka.Route() an error pops up saying Route doesn't exist in polka.
Express Implementation
server.js
const express = require('express');
const users = require('./routes/api/users');
const app = express();
app.use('/users', users);
user.js
const express = require('express');
const router = express.Router();
router.get('/test', (req, res) => res.json({ msg: 'works' }));
module.exports = router;
When /users/test is hit the output is {msg:'works'}. This works for the express implementation. For the polka implementation i changed the word express to polka installing it. The issue arises on the line polka.Router() of user.js. How do i enable this functionality of importing route logic from another file in polka.
The polka micro web server does not implement a difference between routers and the app. In your users.js file simply setup your routes as you would in your server.js file and then module.export. See Below:
Polka Implementation
server.js
const polka = require('polka');
const users = require('./routes/api/users');
const app = polka();
app.use('/users', users);
user.js
const polka = require('polka');
const router = polka();
router.get('/test', (req, res) => res.end(JSON.stringify({ msg: 'works' })));
module.exports = router;
Hope this help!
Also, here is a good link to see other differences between Express.js and Polka.js: https://github.com/lukeed/polka#comparisons
Problem - I am not able to get any response from postman when hitting localhost:9000. It should give me a user json back which is in my routes file only for time being. Instead it spits out the following.
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script type="text/javascript" src="/static/js/main.ce2f0561.js"></script>
</body>
Setup
Using create-react-app with express to connect.
My folder structure is
--src React app lives in this
--server
-- index.js
-- express.js
-- controllers
-- routes
-- rs_notes.js
rs_routes.js
'use strict';
module.exports = function(router){
const notesController = require('../controllers/cs_notes');
router.route('/', function(req, res, next) {
// Comment out this line:
//res.send('respond with a resource');
// And insert something like this instead:
res.json([{
id: 1,
username: "samsepi0l"
}, {
id: 2,
username: "D0loresH4ze"
}]);
});
};
express.js
const express = require('express');
const morgan = require('morgan');
const path = require('path');
const app = express();
const router = express.Router();
// Setup logger
app.use(morgan(':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] :response-time ms'));
// Serve static assets
app.use(express.static(path.resolve(__dirname, '..', 'build')));
require('./routes/rs_notes')(router);
// Always return the main index.html, so react-router render the route in the client
router.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, '..', 'build', 'index.html'));
});
module.exports = app;
index.js
'use strict';
const app = require('./express');
const PORT = process.env.PORT || 9000;
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}!`);
});
Full project link - https://drive.google.com/file/d/0B35OQMkRo3KcSHlkeXdWVjVjc0U/view?usp=sharing
My questions or doubts are
Am I passing the router in a right way. We used to pass app in this
way prior to express 4 ? So not sure if same structure works here.
I am able to load it in browser by hitting localhost:9000 (server is run by node server command as configured) but not in postman.
I was able to fix up this stack by learning the use of Router appropriately and moving some code here and there. But it was still not working for base route i.e when I simply do router.get('/', ...). Gives the same error message. So I rather reversed the approach of connecting node and react. I published my efforts on medium for the same reason as two separate posts.
https://medium.com/#kushalvmahajan/i-am-about-to-tell-you-a-story-on-how-to-a-node-express-app-connected-to-react-c2fb973accf2
I'm trying to organize routes in express. But I'm having trouble getting a simple setup to work. I have two files, api.js, which has the routing info, and index.js, which runs the server.
However, when I try this, I get no response on localhost:3000.
api.js
var express = require('express');
module.exports = function() {
var router = express.Router();
router.get('/', function(req, res) {
res.send('im the home page!');
});
return router;
}
index.js
var express = require('express');
var app = express();
var router = require('./api');
app.use('/',router);
app.listen(3000);
console.log('Listening on port 3000!');
However, when I change api.js to this, it works:
api.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.send('im the home page!');
});
module.exports = router;
I don't understand why the bottom api.js works when the top one doesn't. Shouldn't module.exports return the same express Router in both cases?
The difference is that in the first version you're exporting a function that returns the router vs the second version where you're exporting the router itself.
In the first version, Express calls your exported function, passing it req and res, expecting it to somehow handle the request. The exported function of course is not designed to handle a request (it's just creating a router and returning it), so the request times out.