Nodejs middleware in two files - javascript

Hi I have these two files, and trying to call index.js from server.js which works fine and is printing 'on the other side of the code' but it is not going inside the app.get function. Please advise what I am doing wrong
Server.js
const express = require("express")
const bodyParser = require("body-parser")
const app = express()
var routes = require('./api/index.js')
const PORT = process.env.PORT || 3000
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.use('/t', require('./api/index')(app))
var server = app.listen(PORT, function (){
var host = server.address().address
var port = server.address().port
console.log('Middle ware started on address http://%s:%s',host,port)
})
index.js
const express = require('express')
module.exports = function(app) {
console.log('we are in other part of code')
app.get('/',function(req,res){
console.log('we are there')
console.log(res)
})
}

You should use express Router class to create modular route handlers:
Server.js
const express = require("express")
const bodyParser = require("body-parser")
const app = express()
var routes = require('./api/index.js')
const PORT = process.env.PORT || 3000
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.use('/t', routes)
app.listen(PORT, function (){
var host = server.address().address
var port = server.address().port
console.log('Middle ware started on address http://%s:%s',host,port)
})
index.js
const express = require('express')
const router = express.Router()
router.get('/',function(req,res){
console.log('we are there')
res.send('successfully get /t')
})
module.exports = router;

Your approach is not right try this way
server.js
const express = require("express")
const bodyParser = require("body-parser")
const app = express();
const PORT = process.env.PORT || 3000
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.use('/t', require('./api/index.js'));
var server = app.listen(PORT, function (){
var host = server.address().address
var port = server.address().port
console.log('Middle ware started on address http://%s:%s',host,port)
})
index.js
const express = require('express');
router=express.Router();
router.get('/',function(req,res){
console.log('we are there')
console.log(res)
res.send('success')
});
module.exports=router;

Server.js
const express = require("express")
const bodyParser = require("body-parser")
const app = express()
var routes = require('./api/index.js')(app) // Pass the app
const PORT = process.env.PORT || 3000
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.use('/t', routes) // change this to routes
var server = app.listen(PORT, function (){ var host = server.address().address var port = server.address().port
console.log('Middle ware started on address http://%s:%s',host,port) })
index.js
const express = require('express')
module.exports = function(app) {
console.log('we are in other part of code')
app.get('/',function(req,res){
console.log('we are there')
console.log(res)
res.json({success : true});
})
}

Related

routing error Cannot Get /api/name student activity

I'm trying to recreate a Note Taking App using Express. My code follows the instructor's example but when I deploy it and try to add a new note I get the error cannot get/api/name...I am not sure what I am doing wrong.
enter code here
const fs = require('fs');
const path = require ('path');
const express = require('express');
const dbJson = require('./db/db.json')
const {v1 : uuidv1} = require('uuid');
const PORT = process.env.PORT || 3001;
const app = express();
app.use(express.urlencoded({extended: true}));
app.use(express.json());
app.use(express.static("public"));
app.get('/notes', (req, res) => {
res.sendFile(path.join(__dirname, './public/notes.html'));
});
app.get('/api/notes', (req,res) => {
const dataNotes = fs.readFileSync(path.join(__dirname, './db/db.json'), "utf-8");
const parseNotes = JSON.parse(dataNotes);
res.json(parseNotes);
});
Add at the end: app.listen(PORT);
That will work. The problem was that you didn't start the server

Node.js Express GET request does not work even though the same request with POST works fine

GET request return 404 error but POST request to the same url works fine I could not figure out the reason.
this is the server setup:
images.route.js
const express= require('express');
const controllers = require('./controllers');
const router= express.Router();
const upload = require('../../lib/uploads.controller');
router.get('/', (req, res)=> res.send('get request'))
router.post('/', controllers.getAll);
module.exports= router;
route.js
const express = require('express'),
router = express.Router();
const albumRoutes = require('./albums/album.route');
const imageRoutes= require('./images/index');
router.use('/albums', albumRoutes);
router.use('/images', imageRoutes);
module.exports= router;
server.js
let express = require('express'),
cors = require('cors'),
bodyParser = require('body-parser');
let history = require('connect-history-api-fallback');
const userRoute = require('./routes/router');
const app = express();
app.options('*', cors())
app.use(cors());
app.use(history());
app.use(express.json({limit:
'50mb'}));
app.use(express.urlencoded({
extended: true,
limit: '50mb',
parameterLimit: 1000000
}));
app.use('/api', userRoute)
const port = process.env.PORT || 4000;
app.listen(port, () => {
console.log('Connected to port ' + port)
})
I have been searching for a solution but I could not find any reason.
I even installed different REST API apps like postman and insomnia just in case, but it is the same

I get the error that the body is not defined in expres?

express js the body undefined error
I shared the files below. I got very angry. No error appears. Please help me.
Although I do it again I get the same error
I searched a lot but none of the solutions worked.
main.js
const express = require('express')
const router = express.Router()
router.get('/', (req,res)=>{
res.render('site/index')
})
router.get('/login', (req,res)=>{
res.render('site/login')
})
router.get('/register', (req,res)=>{
res.render('site/register')
})
router.get('/postcreate', (req,res)=>{
res.render('site/postcreatepage')
})
router.get('/postupdate', (req,res)=>{
res.render('site/postupdatepage')
})
router.post('/post/post', (req,res)=>{
console.log(req.body)
})
module.exports = router
I checked and searched many times could not solve
app.js
const express = require('express')
const path = require('path')
const app = express()
const port= 3000
const hostname = '127.0.0.1'
const mongoose = require('mongoose')
const main = require('./routes/main')
var bodyParser = require('body-parser');
app.use('/', main)
app.use(express.static('static'))
mongoose.connect('mongodb://127.0.0.1/nodemon_db',{
useNewUrlParser: true,
useUnifiedTopology:true
})
app.engine('handlebars', require('exphbs'))
app.set('view engine','handlebars')
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.listen(port, hostname, ()=> console.log(`Example app listening on port http://${hostname}:${port}/`))
Although I do it again I get the same error
html
<html>
<head>
</head>
<body>
<form action="post/post" method="post">
<input name="title"><br>
<input name="content"><br>
<button type="submit">But</button>
</form>
</body>
</html>
In your route, you have to return a response other wise the request will hang:
main.js
router.post('/post/post', (req,res)=>{
console.log(req.body)
const resObject = {
... do something with req.body ...
};
return res.status(201).json(resObject);
});
In your app entrypoint, set your routes after your config and middleware:
app.js
const express = require('express')
const path = require('path')
const app = express()
const port= 3000
const hostname = '127.0.0.1'
const mongoose = require('mongoose')
const main = require('./routes/main')
var bodyParser = require('body-parser');
/* config */
mongoose.connect('mongodb://127.0.0.1/nodemon_db',{
useNewUrlParser: true,
useUnifiedTopology:true
})
/* Middleware */
app.use(express.static('static'))
app.engine('handlebars', require('exphbs'))
app.set('view engine','handlebars')
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
/* Routes */
app.use('/', main)
app.listen(port, hostname, () => console.log(`Example app listening on port http://${hostname}:${port}/`)

Routes navigation is not working in NodeJs

I am using router in my NodeJs app.When I am trying to navigate it is unable to navigate to the given page.
Register.js is placed in routes folder and server.js is placed in parent directory.
Here is my code:
Server.js
const express = require('express');
const app = express();
app.set('view engine','ejs');
app.use(require('./routes/register'));
const port = process.env.PORT || 3000;
app.listen(port, (req,res) => {
console.log("Server is running at:", +port);
});
Register.js
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
var app = express();
router.use(bodyParser.json);
router.use(bodyParser.urlencoded({extended:true}));
router.get('/users', (req,res) => {
console.log('Hello there');
});
module.exports = router;
Now when I run this code and go to localhost:3000/users nothing happens and not even error shows in console.
Please let me know what I am doing wrong in above code.
Use router.use(bodyParser.json()); in register.js.
You have used body-parser at wrong place. Also you should initiate those with express instances always.
Also check your file name you have imported. Reigster -> register
Updated code:
Server.js
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.set('view engine','ejs');
app.use(require('./Register'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
const port = process.env.PORT || 3000;
app.listen(port, (req,res) => {
console.log("Server is running at:", +port);
});
Register.js
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
router.get('/users', (req,res) => {
console.log('Hello there');
res.sendStatus(200)
});
module.exports = router;

node js post request.body undefined

server.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var session = require('express-session');
var fs = require('fs');
var router = require('./router/main')(app, fs);
var server = app.listen(3000, function(){
console.log('Express server has started on port 3000');
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
router/main.js
module.exports = function(app, fs)
{
app.post('/addUser/', function(req, res){
console.log(req.body);
});
}
I use postman tool!! requets param {"password" : "pass","name" : "dltlsdn"}
but... req.body is undefind.... why..??
Reorder the app.use statement. Earlier you were processing the request before passing through the body-parser.
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var session = require('express-session');
var fs = require('fs');
//body parser before routes
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
var router = require('./router/main')(app, fs);
var server = app.listen(3000, function(){
console.log('Express server has started on port 3000');
});
Hope it helped you.

Categories

Resources