I want to port my site to Netlify, which is a static website hosting. However, I have a ExpressJS server that uses EJS to render and route things and trying to put everything together without EJS is becoming a nightmare.
For example, server.js:
require('dotenv').config()
const express = require('express');
const app = express()
const PORT = process.env.PORT || 3000;
const path = require('path');
const panelRouter = require("./routes/panel.js")
app.set('view engine', 'ejs');
app.use("/assets", express.static(path.join(__dirname, 'views/assets')))
app.use("/panel", panelRouter)
function nocache(req, res, next) {
res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
res.header('Expires', '-1');
res.header('Pragma', 'no-cache');
next();
}
app.get("/", (req, res) => {
res.render("login");
});
app.get("/robots.txt", nocache, (req, res) => {
res.sendFile(path.join(__dirname + '/robots.txt'));
});
app.listen(port=PORT, () => {
console.log(`Listening on: ${PORT}`)
})
and one of the routers im showing, panelRouter (panel.js)
const express = require('express')
const router = express.Router();
router.get("/", (req, res) => {
res.render("../views/panel/home")
})
router.get("/about", (req, res) => {
res.render("../views/panel/about")
})
router.get("/messages", (req, res) => {
res.render("../views/panel/messages")
})
router.get("/achievements", (req, res) => {
res.render("../views/panel/achievements")
})
router.get("/events", (req, res) => {
res.render("../views/panel/events")
})
router.get("/exec", (req, res) => {
res.render("../views/panel/exec/home_exec")
})
router.get("/erg_home", (req, res) => {
res.render("../views/panel/erg_home")
})
module.exports = router;
Does EJS have a way to compile everything to a folder that I can easily deploy to Netlify or other sites that only host static files?
Related
Some context, I'm using Nodejs and Express for my Web Server, I was using nginx but it failed for some reason and I tried to get help in a previous post but nothing.
When I connect to my site http works fine, https gets "The page isn't redirecting properly". When I connect to my site directly with it's IP it has https (ignoring the fact that it's still isn't really trusted since my certificates are linked to my domain) I just am trying to figure out where it's going wrong.
const express = require('express');
const https = require("https");
const http = require("http")
const fs = require('fs')
const bodyParser = require('body-parser');
var cookieParser = require('cookie-parser')
const login = require("../modules/login")
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cookieParser())
app.set('view engine', 'ejs');
app.set('views', '../public/views');
app.use( express.static( "public" ) );
http.createServer(function (req, res) {
res.writeHead(307, { "Location": "https://www.ppealliance.com"});
res.end();
}).listen(80);
https
.createServer(
{
key: fs.readFileSync('Path to Letsencrypt Certificate'),
cert: fs.readFileSync('Path to Letsencrypt Certificate'),
},
app
)
.listen(443, () => {
console.log(https.request)
})
app.get('/', (req, res) => {
login.redirect(req, res)
});
app.get('/admin-login', (req, res, next) => {
res.render('admin-login', { title:'Admin login'});
});
app.post('/admin-login-cookies', (req, res) => {
login.cookiecheck(req, res)
});
app.get('/signup-1', (req, res) => {
res.render('signup-1', { title:'Signup Part One'});
});
app.post('/admin-login', (req, res) => {
login.login(req,res)
});
app.get('/home', (req, res) => {
login.redirect(req, res)
});
I have a project where I try to locally and on Heroku run a MEVN application. Both are not working at the moment.
I have my server.js file in the main folder. Then inside the 'client' folder is the Vue 3 project. Inside there I have run npm run build which created a dist folder containing the index.html file.
When I run both locally and on Heroku I can go to '/api/users' and the JSON is shown in the browser. But when I navigate to '/'
I have tried changing the public in the server.js to dist but this did not fix the problem.
I get the following error: Error: ENOENT: no such file or directory, stat /Users/stephen/Documents/stephen/project/client/build/index.html
My server.js file looks like this:
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const path = require("path");
const cors = require("cors");
const app = express();
//Bodyparser Middleware
app.use(bodyParser.json());
app.enable("trust proxy");
app.use(cors());
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", '*');
res.header("Access-Control-Allow-Credentials", true);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
next();
});
//DB Config
const db = require("./config/keys").mongoURI;
//Connect to Mongo
mongoose
.connect(db, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log("MongoDB Connected"))
.catch((error) => console.log(error));
app.get('/api/users', (req, res) => {
res.json({ user: 'test' })
})
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '/client/build/index.html'));
});
const port = process.env.PORT || 3000;
if (process.env.NODE_ENV === "production") {
app.use(express.static("client/build"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
});
}
app.listen(port, () => console.log("Server starter on port " + port));
res.redirect function is used to redirect the user to another page by clicking a button. But the function's not working. Please find the code below.
const express = require("express");
const bodyParser = require("body-parser");
const request = require("request");
const https = require("https");
const app = express();
app.use(express.static("public"));
app.use(bodyParser.urlencoded({
extended: true
}));
app.get("/", function (req, res) {
res.sendFile(__dirname + "/signup.html");
});
app.post("/failure", function (req, res) {
res.redirect("/");
});
app.post("/success", function(req, res) {
res.redirect("/");
});
app.listen(process.env.PORT || 3000, function () {
console.log("The server is running at port 3000");
});
Try moving
app.get("/", function (req, res) {
res.sendFile(__dirname + "/signup.html");
});
below your other routes and try calling again
Try changing app.post to app.get:
app.get("/success", function(req, res) {
res.redirect("/");
});
In my html I have,
<input name="password" type="password" required class="form-control" id="exampleInputPassword1">
and in my node I have,
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const urlencodedParser = bodyParser.urlencoded({ extended: false })
app.get('/login.html', (req, res) => {
res.sendFile('./login.html', {root: __dirname});
})
app.post('/login', urlencodedParser, (req,res)=>{
req.body.password
})
but, the req.body.password is undefined or empty. How do I make it actually grab what the user is inputting? It does not work for any of them but, I just used password as an example. All the packages were downloaded correctly.
Thanks.
I used the following code:
const express = require("express");
const bcrypt = require("bcrypt");
const bodyParser = require("body-parser");
const app = express();
const jsonParser = express.json();
const urlencodedParser = bodyParser.urlencoded({ extended: false });
// CHANGE THIS TO DATABASE LATER OF USERS
const users = [];
//listen for requests
app.listen(3000);
app.use(express.static(__dirname + "/public"));
app.get("/index.html", (req, res) => {
res.sendFile("./index.html", { root: __dirname });
});
app.get("/login.html", (req, res) => {
res.sendFile("./login.html", { root: __dirname });
});
app.post("/login", jsonParser, (req, res) => {
console.log("Hello");
console.log(req.body.password);
res.json(req.body.password);
});
app.get("/signup.html", (req, res) => {
res.sendFile("./signup.html", { root: __dirname });
});
app.post("/signup", urlencodedParser, (req, res) => {});
app.use((req, res) => {
res.sendFile("./404.html", { root: __dirname });
});
And when I send a POST request to the /login path using the following payload:
{
"password": "Check for Stack Overflow"
}
I get this on the console:
$ node app
Error: ENOENT: no such file or directory, stat '/root/404.html'
Hello
Check for Stack Overflow
I use the following end point: http://2886795314-3000-ollie08.environments.katacoda.com/
And I used POSTMan and got this right now:
Previous Answer...
You have to use res object to send something. For example, to send a JSON structure, you can do:
res.json(req.body.password)
So your code will be:
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const urlencodedParser = bodyParser.urlencoded({ extended: false });
app.get("/login.html", (req, res) => {
res.sendFile("./login.html", { root: __dirname });
});
app.post("/login", urlencodedParser, (req, res) => {
res.json(req.body.password);
});
Also I could see that you are not using a .listen or export of your modules. You may as well need to listen it to a port to run! So use:
app.listen(3000, () => {
console.log("Server started in port 3000!");
});
At the end. So your complete file looks like:
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const urlencodedParser = bodyParser.urlencoded({ extended: false });
app.get("/login.html", (req, res) => {
res.sendFile("./login.html", { root: __dirname });
});
app.post("/login", urlencodedParser, (req, res) => {
res.json(req.body.password);
});
app.listen(3000, () => {
console.log("Server started in port 3000!");
});
Also, please consider reading Express "Hello World" example. It has the best example in the easiest way possible from the original documentation.
req.body.password is kind of like a variable. It 'returns' it's value, but you're not doing anything with what it returns.
It's not clear what you mean with return. If you want to log something to a console, you can do that:
console.log(req.body.password);
I download the https://github.com/SinghDigamber/Angular8MeanstackAngularMaterial
and deployed it.
But while I tried to save the data and review the data, i always get the
GET http://localhost:4200/api 404 (Not Found)
add data to db error picture
get data to db error picture
Angular v8.0.0
mongoDB v4.0.10
nodejs v12.2.0
//app.js
let express = require('express'),
path = require('path'),
mongoose = require('mongoose'),
cors = require('cors'),
bodyParser = require('body-parser'),
dataBaseConfig = require('./database/db');
// Connecting mongoDB
mongoose.Promise = global.Promise;
mongoose.connect(dataBaseConfig.db, {
useNewUrlParser: true
}).then(() => {
console.log('Database connected sucessfully ')
},
error => {
console.log('Could not connected to database : ' + error)
}
)
// Set up express js port
const studentRoute = require('./routes/student.route')
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(cors());
// Setting up static directory
app.use(express.static(path.join(__dirname, 'dist/angular8-meanstack-angular-material')));
// RESTful API root
app.use('/api', studentRoute)
// PORT
const port = process.env.PORT || 8000;
app.listen(port, () => {
console.log('Connected to port ' + port)
})
// Find 404 and hand over to error handler
app.use((req, res, next) => {
next(createError(404));
});
// Index Route
app.get('/', (req, res) => {
res.send('invaild endpoint');
});
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/angular8-meanstack-angular-material/index.html'));
});
// error handler
app.use(function (err, req, res, next) {
console.error(err.message);
if (!err.statusCode) err.statusCode = 500;
res.status(err.statusCode).send(err.message);
});
I think you forgot to export get and post functions for your API routes.
you can create routes like this in studentRoute File.
var express = require('express');
var router = express.Router();
router.get('/', function (req, res, next) {
return "Hello World";
})
router.post('/', function (req, res, next) {
return "Hello World";
})
module.exports = router;````