Routes navigation is not working in NodeJs - javascript

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;

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

Socket.io Page Loading Forever

Note - I'm using Pug to render my pages.
My page, when including the script(src="/socket.io/socket.io.js"), does not stop loading.
Here's the relevant content from my app.js.
const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
All packages are installed correctly.
In my head tag:
script(src="/socket.io/socket.io.js")
script.
var socket = io();
Yet, my page does not stop loading. What have I done wrong here?
Update:
app.js
const path = require('path');
const express = require('express');
const morgan = require('morgan');
const cookieParser = require('cookie-parser');
const AppError = require('./utils/appError');
const globalErrorHandler = require('./controllers/errorController');
const userRouter = require('./routes/userRoutes');
const viewRouter = require('./routes/viewRoutes');
const projectRouter = require('./routes/projectRoutes');
const app = express();
app.set('view engine', 'pug')
app.set('views', path.join(__dirname, 'views'));
//MIDDLEWARES
if (process.env.NODE_ENV === 'development') {
app.use(morgan('dev'));
}
app.use(express.urlencoded({extended: true}));
app.use(express.json());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use((req, res, next) => {
req.requestTime = new Date().toISOString();
next();
});
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'overview'));
})
//ROUTES
app.use('/', viewRouter);
app.use('/api/1/users', userRouter);
app.use('/api/1/projects', projectRouter)
app.all('*', (req, res, next) => {
next(new AppError(`Can't find ${req.originalUrl}.`, 404));
});
app.use(globalErrorHandler);
module.exports = app;
server.js (run by node)
const mongoose = require('mongoose');
const dotenv = require('dotenv');
// mongoose.set('debug',true);
dotenv.config({path: './config.env'})
const app = require('./app');
const DB = process.env.DB.replace('<PASSWORD>', process.env.DBPASS);
mongoose.connect(DB, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true
}).then(con => {console.log('🔗 Connected.')})
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`📈 Running on ${port}.`)
});
const http = require('http').Server(app);
const io = require('socket.io')(http);
io.on('connection', socket => {
socket.on('greeting', msg => {
console.log(msg);
})
});
http.listen(80);
Now that you've shown your code, this part is wrong:
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`📈 Running on ${port}.`)
});
const http = require('http').Server(app);
const io = require('socket.io')(http);
You are creating two separate servers there and binding socket.io to the one that isn't running. Change that above code to this:
const port = process.env.PORT || 3000;
const server = app.listen(port, () => {
console.log(`📈 Running on ${port}.`)
});
const io = require('socket.io')(server);
Earlier attempt to help before OP had shown their actual code.
My guess is that something is messed up in your environment or something is wedged in your OS or something is blocking some requests. To rule things in or out, I would suggest you try this simple app which works just fine for me:
// app.js
const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const path = require('path');
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "temp.html"));
});
io.on('connection', socket => {
socket.on("greeting", msg => {
console.log(msg);
});
});
server.listen(80);
and the HTML file temp.html:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="/socket.io/socket.io.js"></script>
<style>
</style>
</head>
<body>
<button id="myButton">Press Me</button>
<script>
const socket = io();
document.getElementById("myButton").addEventListener("click", () => {
socket.emit("greeting", "hi from client");
});
</script>
</body>
</html>
You put these two files in the same project and you have the server-side socket.io library installed in that project (it should be in node_modules per a normal installation).
Start the server with node app.js in a way that has a server console that you can see output from. Then, from a browser on the same computer, go to http://localhost. It should load a web page with a single button on it. Press that button. You should see a message in the server console that says hi from client each time you press that button.
If this is working, then we would need to see all your project code to see what's wrong with your actual project.
If this isn't working, then we need to know what errors you get. You can try moving this project to a different port in case you have something blocking some things on a particular port. You can reboot your computer in case something in the networking or file system is wedged.

no such file or directory, stat 'C:\idora-photobok\backend\frontend\build\index.html'

So, I got this error while try to ready my application for production. So, my index.js code is
const app = express();
const port = 8000;
const cors = require('cors');
const db=require('./config/mongoose');
const path = require('path')
//library used
const passport = require('passport');
const passportJWT = require('./config/passport-jwt-strategy');
const bcrypt = require('bcrypt');
//middleware
app.use(express.json());
app.use(cors());
//use routes
app.use('/', require('./routes'));
app.use(express.static(path.join(__dirname, '/frontend/build')))
app.get('*', (req, res) =>
res.sendFile(path.join(__dirname, 'frontend', 'build', 'index.html')))
app.listen(port, async function(err){
if(err){
console.log(`error in running of server;${err}`);
}
console.log(`server is running on port:${port}`);
});
This is my file structure. So, If someone know, why this is happening. please reply.
Thanks

Nodejs middleware in two files

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});
})
}

Categories

Resources