Conditionally serve ejs and react.js builds in smae url - javascript

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.

Related

express.js why is root "/" path not working

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

Unable to run server to get my views/signup.html file to run

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.post('/signup', function (req, res) {
// save user details to your database.
res.send('Signed Up!');
});
app.get('/', function (req, res) {
res.send('Hello World!');
app.use(express.static('views'));
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
I am trying to open my views folder as the html of this application. How can I manage to do that?
You should use middleware in between request response cycle. But here you are using
app.use(express.static('views')); after sending the response.
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
// Middlewares
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('view'));
app.post('/signup', function (req, res) {
// save user details to your database.
res.send('Signed Up!');
});
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
This should fix the problem

node.js/express/ejs not rendering root page?

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

Cannot find module express

Im trying to run an express application and im getting the following error:
module.js:471
throw err;
^
Error: Cannot find module './controllers'
this is my app.js:
const express = require('express');
//let passport = require('passport');
//let session = require('express-session');
const app = express();
app.use(express.static(__dirname + '/public'));
app.use(express.json());
app.use(express.urlencoded({extended:false}));
app.get('/', (req, res) => {
res.redirect('index.html');
});
app.post('/', (req, res) => {
})
app.use('/',require('./controllers'));
/*
app.use(express.session({ secret: 'keyboard cat' }));
app.use(passport.initialize());
app.use(passport.session());
*/
app.listen(3000);
I would like to know why im getting this error
this is my application structure:
When you require a directory like this:
app.use('/', require('./controllers'));
...you are technically looking for ./controllers/index.js:
You would have to add the file name, for example:
app.use('/', require('./controllers/route'));

react app with express.js route setup

I was using angular.js and I do this in express.js
app.get("*", function (req, res) {
res.redirect('/#' + req.originalUrl)
})
so that the browser will use the route of angular instead of express. But how to do that with react router? I have 2 folder, named server and client, server folder has express and api logic while client folder simply a react app.
You need to put the path in of the HTML file you are rendering your app to
app.get("/",(res,res) => {
res.sendFile('put the path of the html file you are rendering your app into here');
}
here is an example of a express server.js that works with react
var express = require('express');
var bodyParser = require('body-parser');
var logger = require('morgan');
var app = express();
var PORT = process.env.PORT || 3000;
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.text());
app.use(bodyParser.json({type: 'application/vnd.api+json'}));
app.use(express.static('./public'));
app.get('/', function(req,res){
res.sendFile('./public/index.html');
});
app.listen(PORT, function(){
console.log("Listening on port: " + PORT);
});

Categories