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);
});
Related
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
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
Hi I am trying to send the contents of string stored in mongo db through res.render. However, if I check after sending this string, the tag appears in the form of a string and does not appear in html, so I want to know how to solve it.
router.get("/:id", async function (req, res) {
var article = await Article.findById(req.params.id);
console.log(article);
res.setHeader("Content-type", "text/html");
res.render("articles/article", { article: article });
});
article = "<p>내용입니다.</p>"
here is the working example. You have to install the pug template engine or any other template engine. See the test. pug file and note that if the variable is HTML content then we have to use the syntax "!{para}" or if the variable is a simple string then we can use the syntax "#{para}".
so the folder structure would be like
app.js
views ->test.pug
// app.js file
var express = require('express');
var app = express();
var PORT = 3000;
app.set('view engine', 'pug');
app.use('/', function(req, res, next){
res.render('test', {para : `<p>This is paragraph</p>`});
});
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
// html file test.pug
<div>!{para}</div>
I started my own VPS, and started a web server using NGINX. I have an index.html. How do I create other pages, like an about page, and having it live at www.my-domain-name.com/about/
Does this mean I have to edit my app.js file, if so, how?
Amendment: I added Lazar's suggested amendment to the Express code to get the about.html.
'use strict';
const express = require("express");
const app = express();
// Static css/js files
app.use('/static', express.static('./dist'));
app.get("/", function(req, res) {
res.sendFile( __dirname + '/index.html');
});
app.get("/about", function(req, res) {
res.sendFile( __dirname + '/about.html');
});
const port = 3001;
// Start server
app.listen(port, function() {
console.log("Listening on " + port);
});
In index.html, the link to the about page is:
About me.
Both /about and /about.html don't currently work and receive the error message: Cannot GET /about.html
Edit: I am using forever, so I had to forever restartall
Considering that you are using express, for every created route, create appropriate html page - or use some other thing, like handlebars, etc.
For example you created index.html for "/" route.
For about us route, create aboutus.html
app.get("/aboutus", function(req, res) {
res.sendFile( __dirname + '/aboutus.html');
});
and so on...
For more info check their official web page: https://expressjs.com/
I'm completely new to node.js but i'm trying to implement it on my personal site so that I start learning it. I have the node server running but i'm trying to set up the routing using express.js . All my files are typical static files .html, .js, .cs, .png , etc. Currently, the route gives me my index page on the 'home' page which is goo. If I attempt to navigate to the index of another diectory, I just get the 404 error page. My file structure is like this:
Server.js
package.json
node_modules
-- views (Folder)
-index.html (File in views)
--Projects (Folder in Views)
-index.html (File in Projects)
my Server.js looks like
var express = require("express");
var app = express();
var router = express.Router();
var path = __dirname + '/views/';
router.use(function (req, res, next) {
console.log("/" + req.method);
next();
});
router.get("/", function (req, res) {
res.sendFile(path + "index.html");
});
router.get("/Projects", function (req, res) {
res.sendFile(path + "Projects/index.html");
});
app.use("/", router);
/*app.use("*", function (req, res) {
res.sendFile(path + "404.html");
});*/
app.listen(3000, function () {
console.log("Live at Port 3000");
});
I've looked for the past ~18 hours at various resources and i'm just missing something i'm sure. My current idea of the issue is the navigation links in the html, however I've attempted changing those with no progress.
If you have only public file (like html, css, ..) you can put everything on a /public folder and add this instead of a router.
app.use(express.static('public'))
Doc: https://expressjs.com/en/starter/static-files.html
Every file will be accessible:
/public/my-folder/my-file.png > www.my-dmain.com/my-folder/my-file.png