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
Related
When I use postman to login a user with http://localhost:3000/login but it always run the register function. Code runs ok, it just routes to wrong function. How to redirect it to login when the url is login and vice-versa. Both the login and register functions are in the same authentication.js file.
controllers/authentication.js
exports.register = (req, res) => {
[Some long code here]
});
exports.login = (req, res, next) => {
[Some long code here]
});
routes/index.js
const express = require("express");
const ctrlAuth = require("../../controllers/authentication");
const router = express.Router();
router.post('/', ctrlAuth.register);
router.post('/', ctrlAuth.login);
module.exports = router;
app.js
const userRoutes = require("./app_api/routes/index");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use("/login", userRoutes);
app.use("/register", userRoutes);
module.exports = app;
The reason here is everytime a route starting with login or register hits your express server it is routed to userRoutes file as both login and register path segment use same routing file as per your code.
app.use("/login", userRoutes); // ---> pointing to userRoutes
app.use("/register", userRoutes); // ---> pointing to userRoutes
Once express moves to userRoutes the path segment left to match is "/" and method type POST. And the first route satisfies both the condition. Hence API call always end up being served by the register handler.
// match found here for "/" segment and post method type
router.post('/', ctrlAuth.register);
// --> this route is never reached
router.post('/', ctrlAuth.login);
ANSWER
To overcome this problem you can make these changes in your files.
app.js
Remove these lines:
app.use("/login", userRoutes);
app.use("/register", userRoutes);
Replace With:
app.use("", userRoutes);
routes/index.js
Remove these lines:
router.post('/', ctrlAuth.register);
router.post('/', ctrlAuth.login);
Replace With:
router.post('/register', ctrlAuth.register);
router.post('/login', ctrlAuth.login);
i have a node.js back-end with express sever.
i have routes called templete.rpoutes.js:
const express = require("express");
const templateCtrl = require("../controllers/template.controller");
const router = express.Router();
router.route("/createtemplate").post(templateCtrl.createTemplate);
router.route("/uploadFinalTemplate").post(templateCtrl.uploadFinalTemplate);
// beneath are the routes with issue
router.route("/:templateId/productInfos").get(templateCtrl.productInfos);
router.route("/:templateId").get(templateCtrl.Read);
// router.param("templateId", templateCtrl.templateByID);
module.exports = router;
I have the defined method in template controller where i'm just logging stuff. no backend logic is there yet. so I expect when I make a call to these end point, i should get those logs displayed
I have configured express server as:
app.use("/api/template", templateRoute);
app.use("/api/productInfo", productInfoRoute);
app.use('/api/sendInformation', Notify)
// PORT
const port = process.env.PORT || 5000;
const server = app.listen(port, () => {
console.log("Connected to port " + port);
});
Note: the app is express.router() method and the controllers are required correctly and the other end-points work for the same controller.
so when I send a get request from postman to localhost:5000/api/template/5f870cd3b02fd77d0a576a54 I get a 404 and Not found in my console like this: (Plus the server is running)
as described in the documentation https://expressjs.com/en/guide/routing.html#express-router
const router = express.Router();
router.post("/createtemplate",templateCtrl.createTemplate);
router.post("/uploadFinalTemplate",templateCtrl.uploadFinalTemplate);
router.get("/:templateId/productInfos",templateCtrl.productInfos);
router.get("/:templateId",templateCtrl.Read);
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
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