I´m trying to create an API Rest in NodeJs with Express.
I have my index.js with the following code:
const express = require('express');
const routesV1 = require('./routes/v1/index');
const app = express();
routesV1(app);
app.listen(4000, () => {
console.log('Running on port: 4000');
});
then i have a routes folder with another "index.js" and a "usersRoutes".
Here´s the code of the userRoutes:
const express = require('express');
const userController = require('../../controllers/v1/UserController');
const router = express.Router();
router.post('/create', userController.createUser);
router.post('/update', userController.updateUser);
router.post('/delete', userController.deleteUser);
router.get('/get-all', userController.getUsers);
module.exports = router;
and the code of the index.js into the routes folder:
const userRoutes = require('./UserRoutes');
const productRoutes = require('./ProductRoutes');
module.exports = app => {
app.use('api/v1/users', userRoutes);
};
but when i´m consuming via Postman, with the following url: http://localhost:4000/api/v1/users/create I´m receiving a 404 error code.
Can anybody help me? thanks
I resolved it adding '/' to the route in routes/index.js
const userRoutes = require('./UserRoutes');
const productRoutes = require('./ProductRoutes');
module.exports = app => {
app.use('/api/v1/users', userRoutes);
app.use('/api/v1/products', productRoutes);
};
Related
I am trying to create a REST API using Express JS.
console.log(req.body) gives undefined as output,
this is my code in routes.js page
const express = require('express');
const router = express.Router();
router.post('/post',async (req,res) => {
console.log("inside post router");
console.log(req.body);
const data = new Model({
name: req.body.name,
age: req.body.age
})
try {
const dataToSave = await data.save();
res.status(200).json(dataToSave)
}
catch(error) {
res.status(400).json({message:error.message})
}
})
This is the code in index.js file
const express = require('express');
const mongoose = require('mongoose');
const routes = require('./Routes/routes');
const app = express();
app.use('/api',routes);
User middlewares ,for parsing the post body in your index.js file
const express = require('express');
const mongoose = require('mongoose');
const routes = require('./Routes/routes');
const app = express();
app.use(express.json()) ; //parsing application/json
app.use(express.urlencoded({extended: false}) ;
app.use('/api',routes);
Make sure to use them ,before you configure your routes
See reference
Ive created an express server and created an api and also ive installed react through vite for my frontend. when I try to connect or load my main html file to the server the console gives that error. Im new to express
Here's My express app code
const express = require("express");
const dotenv = require("dotenv");
const errorMiddleware = require("./middleware/error");
const cookieParser = require("cookie-parser");
const fileupload = require("express-fileupload");
const app = express();
const bodyParser = require("body-parser");
const cors = require("cors");
const path = require("path");
//config for env file
dotenv.config({ path: `${__dirname}/config/config.env` });
app.use(cors());
app.use(express.json({ limit: "50mb" }));
app.use(bodyParser.urlencoded({ limit: "50mb" }));
app.use(cookieParser());
app.use(fileupload());
// Route Imports
const productRoutes = require("./routes/productRoutes");
const userRoutes = require("./routes/userRoutes");
const orderRoutes = require("./routes/orderRoute");
const paymentRoute = require("./routes/paymentRoute");
//using all routes
app.use("/api/v1", productRoutes);
app.use("/api/v1/user", userRoutes);
app.use("/api/v1", orderRoutes);
app.use("/api/v1", paymentRoute);
app.use(express.static(path.join(__dirname, "../frontend")));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "../frontend/index.html"));
});
//error HAndler Middleware
app.use(errorMiddleware);
module.exports = app;
You can't serve your JSX files, you need to first build your front-end, so npm run build and then serve the content of your build folder ( in my case it's dist/ )
app.use(express.static(path.join(__dirname, "./front/dist/")));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "./front/dist/index.html"));
})
So here I have 2 route files and 1 controllers for each.
My first router that is root, is working fine !
but my second route that is /teacher is giving me this error "Cannot GET /teacher"
I literally copy pasted the root route code and changed the variable names still its not working.
following are my files:
server.js
const express = require('express');
const dotenv = require('dotenv');
const root_rt = require('./routes/root-rt');
const teacher_rt = require('./routes/teacherlogin-rt')
dotenv.config();
const uri = process.env.DB_URI;
const port = process.env.PORT;
const app = express();
app.use(express.json());
app.get('/', root_rt);
app.get('/teacher', teacher_rt);
app.listen(port, () =>{
console.log(`server started on http://localhost:${port}`);
});
teacherlogin-rt.js
const express = require('express');
const router = express.Router();
const teacherController = require('../controllers/teacher-cnt');
router.route('/')
.get(teacherController.login);
module.exports = router;
teacher-cnt
module.exports.login = function (req, res) {
res.send('this is teacher login page');
};
Thank you in advance.
When using routers, you shouldn't use app.METHOD() to mount them, but app.use():
app.use('/', root_rt);
app.use('/teacher', teacher_rt);
Make the below change in your teacherlogin-rt.js, it will start working
teacherlogin-rt.js
const express = require('express');
const router = express.Router();
const teacherController = require('../controllers/teacher-cnt');
router.get('/', teacherController.login);
module.exports = router;
server.js
app.use('/', root_rt);
app.use('/teacher', teacher_rt);
I'm getting "Cannot GET /speakers" error on my browser when I am trying to access http://localhost:3000/speakers from the following code:
My Server.js File
const express = require('express')
const path = require('path')
const routes = require('./routes')
const app = express()
const port = 3000
app.set('view engine','ejs')
app.set('views', path.join(__dirname,'./views'))
app.use(express.static(path.join(__dirname,'./static')))
app.use('/', routes())
app.listen(port,()=>{
console.log(`Express server listening on port ${port}!`)
})
My Script.js File
This is my server.js file where I've declared various variables
const express = require('express')
const router = express.Router()
module.exports = () =>{
router.get('/',(request, response) =>{
return response.send('Speakers List')
})
router.get('/:shortname',(request, response) =>{
return response.send(`Detail page of {request.params.shortname}`)
})
return router;
}
My index.js file
const express = require('express')
const speakersRoute = require('./speakers')
const feedbackRoute = require('./feedback')
const router = express.Router()
module.exports = () =>{
router.get('/',(request, response) =>{
response.render('pages/index',{ pageTitle: 'Welcome'})
})
router.use('./speakers', speakersRoute())
router.use('./feedback', feedbackRoute())
return router
}
Can anyone help me on this?
Have you try change './speaker' to '/speaker' ?
// router.use('./speakers', speakersRoute())
router.use('/speakers', speakersRoute())
Ok so I'm trying to redirect the request to a different controller depending on the URL.
My server.js :
const express = require('express');
var app = express();
var router = express.Router();
// controllers
var { loginController } = require('./controller/loginController');
// Specify routes
app.use('/test', loginController);
app.listen(3000, () => {
console.log('started on port 3000');
});
module.exports = { app }
Now if the URL is /test then I would like to redirect the request to loginController, inside loginController I have the following:
const express = require('express');
var router = express.Router();
router.get('/', (req, res) => {
res.send('inside logincontroller');
});
Very short and sweet, however when I run node server.js I get the following error message: Router.use() requires middleware function but got a undefined now I've gone through the Router Use but I'm slightly confused (newbie) I don't have any middleware at present.
Would someone be able to explain to me how I go about redirecting the request to the loginController when the url is /test
server.js
const express = require('express')
// Controllers
var loginController = require('./controller/loginController')
var app = express()
// Specify routes
app.use('/test', loginController)
app.listen(3000, () => {
console.log('started on port 3000')
})
loginController.js
const express = require('express')
var router = express.Router()
router.get('/', (req, res) => {
res.send('inside logincontroller')
})
module.exports = router
Then if you visit http://localhost:3000/test will get the output 'inside logincontroller'