Node express cannot get static file - node.js

This is the picture of my server
https://drive.google.com/file/d/1GA57RyYsc5ik1pSlLhAGtgGjbp_vLFoH/view?usp=sharing
When I go to http://localhost:3000/
I get the error message: Cannot Get/
myserver.js
// TODO: mount the tigers route with a a new router just for tigers
// exactly like lions below
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var _ = require('lodash');
var morgan = require('morgan');
var lionRouter = require('./lions');
var tigerRouter = require('./tigers');
app.use(morgan('dev'))
app.use(express.static('client'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// this is called mounting. when ever a req comes in for
// '/lion' we want to use this router
app.use('/lions', lionRouter);
app.use(function(err, req, res, next) {
if (err) {
res.status(500).send(error);
}
});
app.listen(3000);
console.log('on port 3000');

Whenever you are trying to visit any url on the browser , then browser makes a GET request to that url, in your case you are not sending any response on the url: "http://localhost:3000/. You can try something like this.
app.route('/*')
.get(function(req, res) {
res.sendFile(path.resolve("./client") + '/index.html'));
});

Check the naming you used, it shows myserver.js instead of server.js as in the picture you uploaded.
Check your routing on line 10 of you code
var lionRouter = require('./lions');
var tigerRouter = require('./tigers');
. try this edited codes
server.js
// TODO: mount the tigers route with a a new router just for tigers
// exactly like lions below
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var _ = require('lodash');
var morgan = require('morgan');
var lionRouter = require('./server/lions');
var tigerRouter = require('./server/tigers');
app.use(morgan('dev'))
app.use(express.static('client'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// this is called mounting. when ever a req comes in for
// '/lion' we want to use this router
app.use('/lions', lionRouter);
app.use(function(err, req, res, next) {
if (err) {
res.status(500).send(error);
}
});
app.listen(3000);
console.log('on port 3000');

Express static directory is given client but it is present on parent directory.
So i have resolve this issue with path module and now this will work for you.
// TODO: mount the tigers route with a a new router just for tigers
// exactly like lions below
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var _ = require('lodash');
var morgan = require('morgan');
var path = require('path')
var lionRouter = require('./lions');
var tigerRouter = require('./tigers');
app.use(morgan('dev'))
app.use(express.static(path.join(__dirname, '../client')));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// this is called mounting. when ever a req comes in for
// '/lion' we want to use this router
app.use('/lions', lionRouter);
app.use(function(err, req, res, next) {
if (err) {
res.status(500).send(error);
}
});
app.listen(3000);
console.log('on port 3000');

Your code works fine after commenting the following three lines of your code:
var lionRouter = require('./lions');
var tigerRouter = require('./tigers');
app.use('/lions', lionRouter);
Check if any error is present in LionsJS.

Related

How to get data in express js

For the first time ever i am trying to understand expressJs and I have testing route which returns simple test sentence as JSON, but i can't get in in expressJs.
test.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('https://mysite.ccc/api/test', function(req, res, next) {
res.json(data)
});
module.exports = router;
apps.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var testRouter = require('./routes/test'); ////////////////////////////////////////////////////////here
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/test', testRouter); ////////////////////////////////////////////////////////here
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
I'm not sure but i guess it suppose to show my api sentence in http://127.0.0.1:3000/test instead with:
this command: set DEBUG=myapp:* & npm start it says: 404 not found
and with this command npm start it says request is not defined
what did i do wrong?
👨‍🏫 You can change your test.js with this code below: 👇
var express = require('express');
var router = express.Router();
var axios = require('axios');
/* GET home page. */
router.get('/', async function(req, res, next) {
try {
const response = await axios.get('https://mysite.ccc/api/test');
console.log(response.data);
res.json(response.data)
}catch(ex) {
console.log(ex)
res.status(400).send(ex.message);
}
});
module.exports = router;
I hope it's can help 🙏.
Your test.js file should look like this
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
// I don't see where you defined data, should be smth like: const data = {};
res.json(data);
});
module.exports = router;
Here you define your route, so when you start your app you are able to access the route http://127.0.0.1:3000/test.
You probably want to retrieve data from external website? For this you can use any http package, for example axios.
Your final test.js file will look like:
var express = require('express');
var router = express.Router();
var axios = require('axios');
/* GET home page. */
router.get('/', async function(req, res, next) {
const response = await axios.get('https://mysite.ccc/api/test');
res.json(response.data);
});
module.exports = router;
Note: I hope you somewhere call app.listen(3000) to start your web server.

Emitting and receiving events with Socket.io

I'm trying to emit an event with socket.io on my Node Js server and receive it client-side but I can't get it to work.
This is my server code:
// require our dependencies
var express = require('express');
var expressLayouts = require('express-ejs-layouts');
var bodyParser = require('body-parser');
var app = express();
var port = 3000;
var server = require("http").Server(app);
var io = require('socket.io')(server);
// use ejs and express layouts
app.set('view engine', 'ejs');
app.use(expressLayouts);
// use body parser
app.use(bodyParser.json({extended : true}));
// route our app
var router = require('./app/routes');
app.use('/', router);
// set static files (css and images, etc) location
app.use(express.static(__dirname + '/public'));
// start the server
app.listen(port, function() {
console.log('app started');
});
This is my routes.js code, where the magic should happen:
module.exports = function(io){
// require express
var express = require('express');
var path = require('path');
// create our router object
var router = express.Router();
// export our router
//module.exports = router;
router.post("/", function(request, response) {
console.log(request.body);
io.emit('getupdate',{hello:'world'});
});
// route for our homepage
router.get('/showevent', function(req, res) {
res.render('pages/showevent',{data:exportage});
});
return router;
}
While this is my client-side script:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:3000');
socket.on('getupdate', function (data) {
console.log(data);
});
</script>
On the routes.js file, to get the "io" variable i wrapped all inside a function.
I can't get the message emitted in case of a POST request on my client.
Could you help me to find the issue here ?
Try this:
// require our dependencies
var express = require('express');
var expressLayouts = require('express-ejs-layouts');
var bodyParser = require('body-parser');
var app = express();
var port = 3000;
var server = app.listen(port);
var io = require('socket.io').listen(server);
I am not sure if you have updated this in your own code, but this snippet should pass io to the router:
// route our app
var router = require('./app/routes')(io);
app.use('/', router);

Nodejs Express: Routes in separate files

I write my app.js including all the routes in the main file and everything was working well. After my goal was to make the project more clear by moving the routes in a different files but it is not working.
I'm passing an object instead of a middleware function and I don't know how to fix it in the right way.
So this is my app.js file:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var myRoutes = require('./app/routes/myRoutes.js');
...
//parser for getting info from POST and/or URL parameters
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
//for log requests to console
app.use(morgan('dev'));
app.use('/myRoutes', myRoutes);
app.get('/',function(req,res){
res.end('Welcome Page!');
});
//Server Start
app.listen(port);
console.log('server start at port ' + port);
And the app/routes/myRoutes.js contains the following code:
var express = require('express');
...
var myRoutes = express.Router();
myRoutes.get('/users',function(req,res){
...
});
myRoutes.post('/setup',function(req,res){
...
});
myRoutes.post('/remove', function(req,res){
...
});
module.export = myRoutes;
I also tried this:
var express = require('express');
var myRoutes = express.Router();
myRoutes.route('/')
.get(function(req, res, next){
res.end('myRoute Get');
})
.post(function(req, res, next){
res.end('myRoute Post');
});
module.export = myRoutes;
But again it seems not passing a middleware function.
My second option code
var express = require('express');
var myRoutes = express.Router();
myRoutes.route('/')
.get(function(req, res, next){
res.end('myRoute Get');
})
.post(function(req, res, next){
res.end('myRoute Post');
});
module.export = myRoutes;
is working fine! I just write it in a wrong way
module.export = myRoutes;
isntead of
module.exports = myRoutes;
Hi this is more of additional tips on the question. You main js file would definately need to load a lot of routes and i found importing all of them is a lot of work. Rather use require-dir module to load all the routes like
const loader = require('require-dir');
var app = express();
var routes = loader('./routes');
for (route in routes){
app.use("/"+route,routes[route]);
}
needless to say define all routes inside routes folder and export Router module in each one of them like
var router = express.Router();
router.get(....);
module.exports = router;

Getting invalid URL message in expressjs code

I am new to express.js coding. In my code below i want to access two URLs like http://localhost:3000 and http://localhost:3000/fetch to serve different requests using get method. While accessing the first URL i am able to get the response but while accessing second URL i am getting 404 error. I am unable to figure out the issue, can you please help me out in this.
Below are my files:
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var fetch = require('./routes/fetch');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use('/fetch',fetch);
app.use('/', index);
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('SmartBin: Invalid URL');
err.status = 404;
next(err);
});
modules.export=app;
index.js
var express = require('express');
/* GET home page */
module.exports = (function() {
var path = require('path');
var bodyParser = require('body-parser');
var db = require('./dbclient');
db.dbconnection(null,null,null,null,'smartbin',null);
var router = express.Router();
router.get('/', function(req, res, next) {
//res.render('index', { title: 'Express' });
db.get('devicereg',{}).then(function(v){
//for (i=0; i<v.length-1; i++)
//res.json(v[i]);
res.json(v);//.end();
}).catch(function(v){
console.log('[SmartBin:Error ' + v);
});
});
return router;
})();
fetch.js
var express = require('express');
/* GET home page. */
module.exports = (function(){
var path = require('path');
var bodyParser = require('body-parser');
var router = express.Router();
var db = require('./dbclient');
db.dbconnection(null,null,null,null,'smartbin',null);
router.get('/fetch', function(req, res, next) {
db.get('devicereg',{}).then(function(v){
res.json(v);
}).catch(function(v)
{console.log('[SmartBin:Error ' + v);}
);
});
return router;
})();
I think you could try one of these options:
1. Minor changes:
In your app.js use the app.use('/', index) and app.use('/', 'fetch'). Your route is set inside the index.js and fetch.js files, so it should work, even not having in your app.js the code app.use('/fetch', 'fetch').
In your existing code you probably can access http://localhost:3000/fetch/fetch (because you are declaring /fetch in app.js and then declaring again /fetch in fetch.js file).
2. Pass app by parameter to the route file:
In your app.js, try to require your route files passing your instance of app, instead of app.use('/', index) and app.use('/fetch', fetch).
E.g.:
app.js
var express = require('express');
var app = express();
// Comment these lines
//app.use('/fetch',fetch);
//app.use('/', index);
// Add this lines passing the instance of 'app' you've created
var indexRoute = require('./routes/index')(app)
var indexFetch = require('./routes/fetch')(app)
In your route files, try to adapt as the following:
index.js
module.exports = function(app) {
app.get('/', function(req, res) {
res.send("This is index");
});
}
fetch
module.exports = function(app) {
app.get('/fetch', function(req, res) {
res.send("This is fetch");
});
}
Hope it helps.

ERROR app.use() requires middleware functions: (so how to set router for app.use in express node.js)?

basically im just trying to seprate routes, models, and controller in node.js application.
i have following files to setup very very basic node.js application.
controller/cv.js
module.exports = {
get: function(req, res, next){
console.log("GET REQUESTS")
next();
}
}
routes/cv.js
var express = require('express');
var CvRouter = express.Router();
var CvController = require('../controller/cv')
CvRouter.get('/', function(req, res, next){
console.log("GET REQUESTS")
next();
})
module.export = CvRouter
app.js
const express = require('express');
const bodyParser= require('body-parser')
var path = require('path')
const app = express();
app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())
var router = express.Router();
require('./router')(app)
app.listen(3000, function() {
console.log('listening on 3000')
})
router.js
var CvRouter = require('./routes/cv')
module.exports = function(app) {
app.use([CvRouter]);
};
Basicaly this last file router.js is generting error when i use app.use([CvRouter])
ERROR is: throw new TypeError('app.use() requires middleware functions');
how i can resolve it? i also know its returning object of router. and app.use expecting function in parameter. but how i can achieve my desired MVC pattern of node.js?
as said in comment - you have a typo.
The file routes/cv.js contains module.export instead of module.exports, that makes CvRouter undefined.
Kill the array literal
var CvRouter = require('./routes/cv')
module.exports = function(app) {
app.use(CvRouter);
};

Resources