Im new at nodejs programming and im having a little problem now. When i try to go localhost:3000/ i want to go homeController and index function prints the HTML file.
APP.JS
const express = require('express')
const mongoose = require('mongoose')
const mongodb = require('mongodb')
const app = express();
const homeController = require('./home/homeController.js');
app.get('/', function(req, res) {
res.redirect(homeController.index);
});
app.listen(3000, () => console.log('Example app listening on port 80!'))
HOMECONTROLLER.JS
var path = require("path");
exports.index = function(req, res){
res.sendFile(path.join(__dirname+'/index.html'));
};
console.log('test33');
Also i am using exports to seperate app.js from other controllers. Is this the right way? I have a history with Python Django framework and we used to use URLs to navigate our program.
Thanks.
OUTPUT
Cannot GET
/function%20(req,%20res)%7B%0A%20%20res.sendFile(path.join(__dirname+'/index.html'));%0A%7D
Your problem is that homeController.index is a function, but you're not calling it. Replace:
app.get('/', function(req, res) {
res.redirect(homeController.index);
});
with:
app.get('/', homeController.index);
Your homeController.js exports an index function which requires two parameters reqand res.
So you have to update your app.js accordingly :
app.get('/', function(req, res) {
homeController.index(req, res);
});
edit: by the way, your app is listening to port 3000
Related
I would like to make multiple router settings like the example in ExpressJS Doc.
I have index.js , api1 , api2 like below.
How can I pass the db object from index.js to api1 and api2?
I try with
app.use('/api/v1', require('./controllers/api_v1')(db));
but it shows errors:Router.use() requires a middleware function but got a Object
index.js:
var express = require('../..');
const knex = require('knex');
const config = require('./config');
var app = module.exports = express();
const db = knex(config.db);
app.use('/api/v1', require('./controllers/api_v1'));
app.use('/api/v2', require('./controllers/api_v2'));
app.get('/', function(req, res) {
res.send('Hello from root route.')
});
/* istanbul ignore next */
if (!module.parent) {
app.listen(3000);
console.log('Express started on port 3000');
}
api_v1.js
var express = require('../../..');
var apiv1 = express.Router();
apiv1.get('/', function(req, res) {
res.send('Hello from APIv1 root route.');
});
apiv1.get('/users', function(req, res) {
res.send('List of APIv1 users.');
});
module.exports = apiv1;
api_v2.js
var express = require('../../..');
var apiv2 = express.Router();
apiv2.get('/', function(req, res) {
res.send('Hello from APIv2 root route.');
});
apiv2.get('/users', function(req, res) {
res.send('List of APIv2 users.');
});
module.exports = apiv2;
You could export the db object from a database.js file and require it in the index.js file as well as every other file where you need database access. Or, an easier but uglier method, would be to make the variable global via global.db = db. You could then use db everywhere in your Node.JS application.
I a beginner with Express js and when I reload the server to show the HTML file display "Cannot get" this is photo from the console and its show som errors
this my code server-side:
and this is a photo from git bash and the server is working
and this is my HTML code
help, please
Instead of app.route(), use app.get()
like this
const express = require("express)
const path = require("path")
const app= express()
app.get("/",(req,res)=>{
res.sendFile(path.join(__dirname, './index.html'))
})
app.listen(3000,()=>{
console.log("server running at port 3000")
})
app.route takes a string as an argument and returns a single route - you're passing a callback function, so change your route handling to the following:
// use the appropriate HTTP verb
// since you're trying to serve the `index.html` file,
// `get` should be used
app.route("/")
.get((req, res) => {
res.sendFile(path.join(__dirname, './index.html')
})
Alternatively, you could just do the following:
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, './index.html')
})
Here's a working example:
// thecodingtrain/
// index.js
// home.html
// package.json
const path = require("path")
const express = express()
const app = express()
const PORT = 3000
app.route("/")
.get((req, res, next) => {
res.sendFile(
path.join(__dirname, "./home.html")
)
})
app.listen(PORT, () => {
console.log(`Listening on port ${PORT})
})
Hope this helps.
I want to export my routes in external files.
Everything but the root route is working:
localhost/login -> "Login page"
localhost/ -> empty
server.js:
// SET UP =============
var express = require("express");
var app = express();
var port = 80;
var bodyParser = require("body-parser");
// CONFIG =============
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.urlencoded({'extended':'true'}));
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
// ROUTES =============
var base = require("./routes/base");
app.use("/",base);
// LISTEN =============
app.listen(port);
console.log("Server listening on port " + port);
base.js:
var express = require('express')
var router = express.Router()
//Home
router.get('/', function (req, res) {
res.send('Home page')
})
//Login
router.get('/login', function (req, res) {
res.send('Login page')
})
module.exports = router
You don't need to specify the route on app.use('/', base) instead just supply the router middleware directly to your express app and let the router within base handle the request.
app.use(base)
Uhm, okay I found my problem.
There is an empty index.html in my ./public folder.
You're overwriting the root route with your /login route and only exporting the /login one because of that. If you want to keep all routes in one file I recommend doing something in you base.js file like:
module.exports = function(server){
server.get('/', function(request, response){
response.send('Home page.');
});
server.get('/login', function(request, response){
response.send('Login page.');
});
}
Then in the server.js file import the route using:
require('./routes/base.js')(app);
This immediately imports the routes and calls their functionality on the Express server you crated :)
var express = require('express'),
app = express(),
db = require('./db'),
bodyParser = require('body-parser'),
controller = require('./controller');
app.use(express.static('../public'));
app.get('/server', function (req, res) {
console.log(__dirname);
res.sendFile('/../client/index.html');
});
I have this express server set up but using the code above I get "Cannot GET /" when I view localhost:portnumber. If I change the GET method to:
app.get('/', function(req, res) {
res.sendFile(__dirname + '../client/index.html');
});
I get "'C:\Users\TC\Documents\Desktop\myapp\multiplayerWebSite\server..\client\index.html' at Error (native)" and if I change it to:
app.get('/', function(req, res) {
res.sendFile('../client/index.html');
});
I get "TypeError: path must be absolute or specify root to res.sendFile"
Error: ENOENT: no such file or directory
The server was working perfectly when I had everything in the root directory, but I wanted to change the folder structure to make it more neat/professional. If anyone could tell me what I'm doing wrong I'd appreciate it greatly. Thank you in advance!
You can use path module, there is a join method that take multiple paths to make one.
Exemple if you do:
path.join('test/musicfolder', '../videofolder/allreadyseen')
you will get 'test/videofolder/allreadyseen' .
you can see all the doc here : https://nodejs.org/api/path.html
var express = require('express'),
path = require('path'),
app = express(),
db = require('./db'),
bodyParser = require('body-parser'),
controller = require('./controller');
app.use(express.static(path.join(__dirname, '../public')));
app.get('/server', function (req, res) {
console.log(__dirname);
res.sendFile(path.join(__dirname, '../client/index.html'));
});
very new to nodejs here. I've tried to put routes in app.js without problem. However, after moving all the routes to a separate file under PROJECT_DIR/src/routes/index.js, and then I open the page in browser it says "Cannot GET /wines". Here's code in app.js and src/routes/index.js:
// app.js
var express = require('express');
var app = express();
var path = require('path');
global.app = express();
require('./src/routes/index');
// also tried: require(path.join(__dirname, './src/routes/index'));
global.server = app.listen(3000, '0.0.0.0', function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
// ./src/routes/index.js
// tried console.error(app); and it printed all the stuff about app in the server log
app.get('/wines', function(req, res) {
res.send([{name:'w1'}, {name:'w2'}]);
});
app.get('/', function (req, res) {
res.send('Hello World!');
});
I'm sure I'm missing something. Any help is appreciated!
Problem
Honestly, I am not sure why what you are doing does not work.
The file can be found because otherwise, Node would throw an error, and the fact that you can access app from the routes file means app is accessible.
I have a suspicion that this may be due to garbage collection -- because you do not hold a reference to the module, it may be preemptively destroyed.
What's more, there is a construct in Express called a router that probably exists for this exact purpose.
Solution
While I'm not sure about the problem I am sure about the solution -- use a router, like this:
var express = require('express');
var router = express.Router();
router.get('/wines', function(req, res) {
res.send([{name:'w1'}, {name:'w2'}]);
});
router.get('/', function (req, res) {
res.send('Hello World!');
});
module.exports = router;
And then in your app.js file, do this:
var routes = require('./routes/index');
app.use('/', routes);
Another benefit of routers is that you do not have to pollute the global object anymore..
You need to use export in index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index');
});
module.exports = router;
and use it like this in app.js
var router = require('./src/routes/index');