PATH IS NOT DEFINED - html

i am setting up the route for my application, the file i want to target is signup.html located in code-FE folder while the file i am working on server.js is located in BE folder as shown below
enter image description here
and every time I "res. send" to file signup.html it shows error path is not defined. this is my code, can someone show me how to fix it
const express = require('express')
const app = express()
const port = 3000
app.set('view engine', 'html');
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '../code-FE', 'signup.html'));
})
app.listen(port, () => {
console.log(`Example app listening on port http://localhost:${port}`)
})

You forgot to import the path module
Add this const path = require('path'); for node v < 18 or const path = require('node:path'); for node v 18

Related

Showing HTML file in Node js Application

I am new on Node.js and I have app.js file like:
const express = require('express');
const app = express();
const port = 8080;
app.get('/', (req, res) => res.send('Hello World'));
app.listen(port);
console.log(`App running on http://localhost:${port}`);
I also have index.html file in the same folder with app.js. Here there is a HTML5 website.
When I run the project I can see Hello World text in browser, How can I show this HTML file from my app.js so when I deploy it, it should show me responsive HTML file instead of Hello World?
I tried
app.get('/',function(req,res) {
res.sendFile('index.html');
});
But didn't see a difference.
To make your code example work you'll need to specify an absolute path, try using this:
res.sendFile(__dirname + "/index.html");
Another way would be to use EJS (https://ejs.co/)
In your example, you could do the following:
Install EJS:
npm install ejs
Set the View Engine to EJS:
app.set('view engine', 'ejs')
- Move your index.html file to a folder called "views" and also rename the file to index.ejs
views/index.ejs
In your app.get() handler, use:
res.render('index')
Final Result:
const express = require("express");
const app = express();
app.set("view engine", "ejs");
const port = 8080;
app.get("/", (req, res) => {
res.render("index");
});
app.listen(port, () => {
console.log(`App running on http://localhost:${port}`);
});
(note: I also moved your console.log to inside app.listen)
I found this on another stack overflow question, it should work
fs.readFile(__dirname + '/views/test.html', 'utf8', function(err, text){
res.send(text);
});

How do 'no code' websites publish webpages for each user? [duplicate]

I am used to working on httpd ( Apache ) which provides a way to configure subdomains which is mapped to a directory.
How can I do the same thing in Connect.js/Express.js ? I see that the only thing that I have is routes which I am not sure how I can use to configure sub domains. I have subdomains like m.mysite.com, sync.mysite.com
Can someone help ?
Or alternatively you could use vhost.
Then, create several sites in their own directory and export the express app, eg. /path/to/m/index.js:
var app = express()
/* whatever configuration code */
exports.app = app
// There is no need for .listen()
And then handle all requests with the following app:
var vhost = require('vhost');
express()
.use(vhost('m.mysite.com', require('/path/to/m').app))
.use(vhost('sync.mysite.com', require('/path/to/sync').app))
.listen(80)
Note that /path/to/m and /path/to/sync can be absolute paths (as written above) or relative paths.
You could append a subdomain to a request and then check for it in subsequent next() calls.
I got the following code from > http://groups.google.com/group/express-js/browse_thread/thread/b04bbaea7f0e8eed (so full credit to the original author)
app.get('*', function(req, res, next){
if(req.headers.host == 'some.sub.domain.com') //if it's a sub-domain
req.url = '/mysubdomain' + req.url; //append some text yourself
next();
});
// This will mean that all get requests that come from the subdomain will get
// /subdomain appended to them, so then you can have routes like this
app.get('/blogposts', function(){
// for non-subdomain
});
app.get('/mysubdomain/blogposts', function(){
// for subdomain
});
I have recently came across this problem, and wrote a module to help with it using express 4. https://www.npmjs.org/package/express-subdomain.
Example - api subdomain.
var express = require('express');
var app = express();
var router = express.Router();
//api specific routes
router.get('/', function(req, res) {
res.send('Welcome to our API!');
});
router.get('/users', function(req, res) {
res.json([
{ name: "Brian" }
]);
});
app.use(subdomain('api', router));
app.listen(3000);
Check out the module on npm to see more examples.
I created a module to help with subdomains in Express: https://github.com/WilsonPage/express-subdomain-handler
Do as I say, create two express app in different folder.
For example:
one app in /blogsite directory
const express = require("express");
const blog = express();
blog.get("/", (req, res) => {
res.send("BLOG SECTION");
});
blog.get("/allblogs", (req, res) => {
res.json([
{ title: "csgo major boston", description: "Best CSGO major ever" },
{ title: "Blast pro series", description: "Coolest series of CSGO" },
]);
});
module.exports = { blog };
and another one in /portfolio directory
const express = require("express");
const portfolio = express();
portfolio.get("/", (req, res) => {
res.send("PORTFOLIO SECTION");
});
portfolio.get("/resume", (req, res) => {
res.send("HERE'S MY RESUME");
});
module.exports = { portfolio };
Now create a main app in the outer folder and import the other two express apps that you just made in /blogsite directory and /portfolio directory.
And in the main app do this,
const express = require("express");
const vhost = require("vhost");
const { blog } = require("./blogsite");
const { portfolio } = require("./portfolio");
const app = express();
// BLOG AND PORTFOLIO
// url: http://blog.localhost:3002/
// url: http://blog.localhost:3002/allblogs
// url: http://portfolio.localhost:3002/
// url: http://portfolio.localhost:3002/resume
app
.use(vhost("portfolio.localhost", portfolio))
.use(vhost("blog.localhost", blog));
// MAIN APP ROUTES OR ENDPOINTS
// url: http://localhost:3002
// url: http://localhost:3002/myhobbies
app.get("/", (req, res) => {
res.send("MAIN APP SECTION");
});
app.get("/myhobbies", (req, res) => {
res.send("MAIN APP -> myhobbies section");
});
app.listen(3002, () => {
console.log("started listening");
});
fileStructure at the end should be looking like this
main(folder)
index.js (main express app which you need to run using node or nodemon)
blogsite(folder that I talked about for blog.localhost)
index.js (blog express app)
portfolio(folder)
index.js (portfolio express app)
I've had this exact same requirement for a project I was working on and ended up throwing together a middleware-based solution. It allows you to define routers and view folders per subdomains.
Check it out on NPM https://www.npmjs.com/package/express-multiview
or GitHub https://github.com/daryl-cecile/express-multi-view#readme

GET to CSS returns 404

So I recently moved my website from a single-page website to an express server. Now I changed the file paths, but I cannot get my css and js files to load.
As seen in the developer console, the GET request to https://<website>.com/public/css/main.css returns a 404.
This is the css link:
<link rel="stylesheet" type="text/css" href="../public/css/main.css">
This is my server:
const express = require('express');
const app = express();
const getpages = require('./router/getpages.js');
app.use('/', getpages);
app.use(express.static('public'));
// 404's
app.use((req, res) => {
res.status(404).send('Page not found or non-existant.<br><br>Home');
});
app.listen(3000, console.log('Running on port 3000'));
This is ./router/getpages.js:
const router = require('express').Router();
const path = require('path');
router.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '../views/', 'index.html'));
})
module.exports = router;
This is the file structure:
Note, I could not find any other questions that helped me, before this is marked as a dupe again.
As can be seen from the documentation, you should not have public in the route
https://<website>.com/css/main.css should work as expected.
refer : https://expressjs.com/en/starter/static-files.html
For example, use the following code to serve images, CSS files, and
JavaScript files in a directory named public:
app.use(express.static('public'))
Now, you can load the files that are
in the public directory:
eg : http://localhost:3000/images/kitten.jpg
Express looks up the files relative to the static directory, so the
name of the static directory is not part of the URL.

Next.js stylesheet is not loaded

I'm using Next.js to build my website. I modify the server using express.js server so I have server.js on my root folder of my project.
When I started the server npm run dev which run node server.js, my home page renders correctly. But when I navigate to some of other page in my website, the css is not loaded. But if I refresh the page, it will load the css and the problem is gone
const express = require('express')
const next = require('next')
const dev = process.env.NODE_ENV !== 'production'
const app = next({dev})
const handle = app.getRequestHandler()
app.prepare().then(() => {
const server = express()
server.get('*', (req, res) => {
return handle(req, res)
})
const port = process.env.PORT || 3000
server.listen(port, err => {
if (err) throw err
console.log(`> Ready on port ${port}...`)
})
})
Here's my server.js file. I think there is no problem with the code.
I use #zeit/next-less package for compiling my LESS stylesheet
Please help
Thanks
Check this out: https://github.com/zeit/next-plugins/issues/282
In short as a workaround:
Create an empty CSS file in /static/ directory.
Import it in _app.js:
import '../static/jank-empty.css';
I hope that it would help.
For me the issue was that the nextjs wasn't loading the rel=stylesheet link tags. It was only able to load rel=preload link tags.
so I did a workaround like this:
document.querySelectorAll("link[rel='preload'][as='style']").forEach(link => link.rel = "stylesheet")

Fetching data from mongoDB and displaying on HTML

I'm having trouble understanding how to fetch data from the MongoDB database and display it on HTML. I already have set for the data.
this is the the server.js file.
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser')
const mongoose = require('mongoose');
const app = express();
//map global promise - get rid of warning
mongoose.Promise = global.Promise;
// connect to mongoose
mongoose.connect('mongodb://localhost/peppino-calc', {
useMongoClient: true
})
.then(() => { console.log('MongoDB connected...')})
.catch(err => console.log(err));
//Load salaryModel
require('./modles/Idea.js');
const Idea = mongoose.model('ideas');
//body parser middleware
app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json())
// post history page
app.get('/history', (req, res) => {
Idea.find({})
.sort({date:'desc'})
res.sendFile(__dirname + '/js/newJs/history.html')
})
//process form
app.post('/ideas', (req, res) => {
let errors = [];
if(errors.length > 0) {
console.log(errors[0]);
} else {
const newUser = {
amount: req.body.totalamount,
hours: req.body.totalhours,
salary: req.body.totalsalary,
tip: req.body.totaltip,
date: req.body.datetotal
}
new Idea(newUser)
.save()
.then(idea => {
res.redirect('/history');
})
}
});
app.use(express.static(path.join(__dirname, './js/newJs')));
app.set('port', process.env.PORT || 5700);
var server = app.listen(app.get('port'), function() {
console.log('listening on port ', server.address().port);
});
my goal is to display the data from the database in a specific html page.
any help?
You have to use a template engine in order to display data in an html page, there are many template engines, you can choose one from this link
Here is an example using pug:
1- install pug
npm install pug --save
2- set view directory:
app.set('views', path.join(__dirname, 'views'));
3- set pug as the default view engine
app.set('view engine', 'pug');
4- create history.pug inside views folder
doctype html
html
head
body
table
thead
tr
th Name
th date
tbody
each idea in ideas
tr
td= idea.name
td= idea.date
5- pass data from express to pug:
app.get('/history', (req, res) => {
let ideas = Idea.find({})
.sort({date:'desc'}).exec( (err, ideas) => {
res.render('history', ideas);
});
})