I'm using node.js, express, and ejs as a development environment. I've run into an issue where my main page isn't rendered. However, other pages are rendered. I get absolutely no return when I access http://127.0.0.1:9999. However, I get the proper response when I access http://127.0.0.1:9999/about. I replaced my normal page with a very simple test page to check if there was something wrong it. Nope. No change. I can only conclude that the path '/' (or '') isn't seeing the request.
Can anyone see the problem? Thanks
app.js
const path = require("path");
const express = require("express");
const ejs = require("ejs");
const app = express();
const port = 9999;
const viewsPath = path.join(__dirname, "./views");
app.set("view engine", "ejs");
app.set("views", viewsPath);
app.use(express.static(path.join(__dirname, "/public")));
app.get("/", function(req, res) {
console.log("index accessed");
res.status(200).render("partials/test.ejs");
});
app.get("/about", function(req, res) {
console.log("about accessed");
res.status(200).render("partials/test.ejs");
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
test.ejs
<h1>This is a test page</h1>
I added the following route, and the path is not matched.
app.get("*", function(req, res) {
console.log("* accessed");
res.status(200).render("partials/test.ejs");
});
In the meanwhile it is possible to use:
app.use(express.static(app_path, {
index: false
}));
Credits to
Related
I'm learning express.js at the moment. Rigth now, my root "/" path is not working anymore. When I check localhost:3000/ nothing is displayed, just a blank page. I can't figure out why. When I use other pathes like e.g. "/hello" its working. Strangely I copied the code from an udemy lessons and its the exact same code. In the udemy lessons its working.
Where is my mistake? What did I do wrong?
I want localhost:3000/ to display my response "Hello"
const express = require('express');
const path = require('path');
const hoganMiddleware = require('hogan-middleware');
const app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'mustache')
app.engine('mustache', hoganMiddleware.__express)
app.use(express.static(path.join(__dirname, 'public')))
app.get('/hello' , (req, res, next) => {
res.send('Hello from hello');
})
app.get('/', (req, res, next) => {
res.send('Hello')
})
app.listen(3000, () => {
console.log('server is running on ' + 3000);
});
I want to serve ejs and react.js conditionally to the user. When the user visits the page he would be landed to a login page which would be served from ejs. Once he logins in successfully which would be through an OAUTH, I want to serve the react.js build of the app.
const path = require("path");
const express = require("express");
const app = express(); // create express app
let ejs = require('ejs');
// app.get('/login', (req, res) =\> {
// app.set("view engine", "ejs");
// res.render('index');
// });
app.use('/', express.static(path.join(\__dirname, "..", "build"))); //React.js prod build path
app.use('/', express.static("public"));
app.get('\*', (req, res) =\> {
if(true) {
app.set("view engine", "ejs");
res.render('index');
} else {
res.sendFile("index.html", { root: path.join(\__dirname, "..", "build") });
}
});
// start express server on port 3000
app.listen(3000, () =\> {
console.log("server started on port 3000");
});
Any help regarding the serving of both apps would be highly appreciated.
Sorry if this question is vague but I really don't know what code to present.
I have a Heroku webpage which is running fine. I am using reach-router to navigate from one page to another on button clicks: <button onClick={() => navigate('/intro')}>Click</button>. When I do this the url changes appropriately and my content is visible. However if I type in the exact same url I get an error saying Cannot GET /intro. This error even happens if I use the button click to navigate and then reload the page.
It's my understanding that app.use(express.static('build')); will serve my static files.
So why can I visit pages if I start at my root url and navigate from there but I can't enter a url and travel to that page?
The website is live here https://build-a-wedding.herokuapp.com/
Adding more details on my server.js
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const cors = require('cors');
const sessionMiddleware = require('./modules/session-middleware');
require('dotenv').config();
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(sessionMiddleware);
app.use(cors());
// Serve static files
app.use(express.static('build'));
app.use(express.static(path.resolve(__dirname, '..', 'build')));
const users = require('./routes/users.router');
const dataFetch = require('./routes/data.router');
const venues = require('./routes/venues.router');
app.use('/users', users);
app.use('/location', dataFetch);
// app.use('/', auth);
app.use('/venues', venues);
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
console.log(`Listening on port: ${PORT}`);
});
When I navigate programmatically here is what i see for my sources
When I type in the same URL here is the source tree
Just create a static.json file at the root of your React project with the following content:
{
"root": "build/",
"clean_urls": false,
"routes": {
"/**": "index.html"
}
}
This question is possibly duplicated
Make sure that your express app are listening to these routes and sending response to them.
Example:
app.get('/intro', function (req, res) {
res.send(pathToPage);
});
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'm building my first Node application and having some trouble displaying the page that I want with a GET request. I have installed ejs (opinions welcome on that!) so my understanding is that I do not need to define the 'views' folder. Here is my routes file so far:
const express = require('express');
const router = express.Router();
const Event = require('../models/event')
router.get('/'), function(req, res, next){
/* Event.find({}).then(function(events){
res.send(events);
});
});*/
res.render('../../index');
};
router.post('/events', (req, res) => {
Event.create(req.body);
res.send({type: POST})
});
module.exports = router;
The database is connecting just fine, which I can see with the code that I have commented out in the get request. But for some reason I can't render my index file. My file structure is as follows:
File tree:
So I need to go up two levels, correct? I tried index, index.ejs, ../index, views/index, nothing has worked. What am I doing wrong?
EDIT: this is my server.js:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const routes = require('./routes/index');
var path = require("path");
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(bodyParser.json());
app.use(express.static('public'));
app.use(routes);
app.use(bodyParser.urlencoded({extended: true}))
mongoose.connect('mongodb://junk:junk#ds141242.mlab.com:41242/alaska-events');
app.listen(3000, () => {
console.log('listening on 3000')
});
views folder is placed directly in root folder, and using we app.set('views', path.join(__dirname, 'views')); point it to views folder. So in render directly mention the view name.
router.get('/', function(req, res, next){
res.render('index');
});
Thanks for your help everyone, turned out to be just a typo. router.get('/'), function(req, res, next) should have been router.get('/', function(req, res, next).