Showing index.html file with node.js - javascript

This is my first topic, and I'm not really that great with js, but how do I get my index.html file to show up? This is what I have.
const express = require("express");
const app = express();
const PORT = process.env.PORT || 3000
app.get("/", function (req, res) {
res.send("hello!")
});
app.listen(PORT, function () {
console.log("Server is running on localhost:" + PORT);
});
app.js and index.html are in the same directory. Thanks!

You can try using the following code into app.get function
res.sendFile(__dirname+/index.html");

Related

How can I display a HTML file in app.post method in express js

var express = require('express');
var app = express();
var path = require('path');
var port = 3000;
app.use(express.static(__dirname));
app.get('/', (req, res) => {
res.send("Im fine");
});
app.get('/about' ,(req,res) =>{
res.sendFile(path.join(__dirname, 'modalbox.html'));
res.end();
})
app.listen(port, () =>{
console.log(`server running in https://localhost/${port}`);
})
modalbox.html isn't serving in "localhost:3000/about"
I can't find, why this html file isn't serving in this link, plz someone gimme the answer
trying to server the html file, but can't serve the file
Problem 1: The question is POST but the code is using GET.
Problem 2: Using res.end() end the response immediately while the file is being sent. res.sendFile is enough.
app.post('/about', (req, res) => {
res.sendFile(path.join(__dirname, 'modalbox.html'));
})
Problem 3: You've already serve static file using app.use(express.static(__dirname)). Just hit localhost:3000/modalbox.html and you can see your file

node, express, body-parser - can't read js file from src

may be its dumb question but I can't find answer yet. :(
I made app using create-react-app, and server file:
server.js
const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
const path = require('path');
const PORT = process.env.PORT || 3000;
const app = express();
const p = path.parse(__dirname);
app.use(express.static('public'));
app.get('/', (req, res) => {
const filePath = path.join(p.dir, 'src', 'index.js');
fs.readFile(filePath, {encoding: 'utf-8'},(err, data) => {
if (err) {
throw err;
}
res.send(data);
});
});
app.listen(PORT, () => {
console.log(`Started at port ${PORT}`);
});
tryied to read index.js file from app src directory but all i got in browser is plain text. I can only run static files from public directory. What i did wrong and how should i run js files of react app using express in node?
You need to send the index.html file that is built by react. A browser can only open a web page from a html file.
You need to first build your react app using npm run build
Then serve it with express with something like
app.get('*', (req,res) => {
res.sendFile('/build/index.html'); // wherever react creates the index.html
});
To give you a basic idea on express,
const express = require('express')
const app = express()
app.get('', (req, res) => {
res.render('index') // index is an html file or a template (ejs, hbs, etc..)
})
// You can't directly send js files
app.get('/info', (req, res) => {
res.render('info', {
title: 'info page',
message: 'welcome to the info page'
})
})
// You can't directly send js files
app.listen(3000, () => {
console.log('Server is up on port 3000.')
})
If you want to send json
const leaderboardHistory = require("relativepath/leaderboardHistory.json")
app.get("/leaderboardhistory", function(req, res){
res.render("leaderboardhistory", {leaderboardHistory : leaderboardHistory});
});

error when get html file by express js and javascript

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.

Getting Error when I deploy ext js app in node server

I am trying to deploy my ext js app in node server. Steps i have followed.
1.Created a Extjs app using sencha cmd and had used sencha app build to build my app
Once after building successfully i have taken my app in build-->production folder to my node server folder.
below screenshot contains dbview(client) files
When i start my node server and run my applicaiton using http://localhost:3000 getting following error in my console
Please find my server code
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.sendFile(__dirname+"\\dbview\\index.html");
})
var server = app.listen(3000, function () {
var host = server.address().address
var port = server.address().port
console.log('Example app listening at http://%s:%s', host, port)
})
Help me with the problem
You need to mount the directory so that express knows to look for static content there, or you could go the long way about it and create a specific route handler for that file:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.sendFile(__dirname+"\\dbview\\index.html");
});
// THIS IS WHAT YOU NEED
app.use(express.static(__dirname));
// OR THE LONG WAY
app.get('/app.json', function(req, res) {
var options = {
root: __dirname,
dotfiles: 'deny',
headers: {
'x-timestamp': Date.now(),
'x-sent': true
}
};
res.set('Content-Type', 'application/json');
res.sendFile('app.json', options);
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
See the Express Documentation for further details.

How to create subpages with node.js using Amazon EC2 and heroku

I'm a beginner programmer and pretty new to Node.js.
I managed to setup a single static page by using AWS EC2 and Heroku, but I need help making other subpages. ie. mysite/blog or mysite/archive.
I started out with a simple web.js file I got from a sample node app which was:
var express = require('express');
var app = express();
app.use(express.logger());
app.get('/', function(request, response) {
response.send('Hello World!');
});
var port = process.env.PORT || 5000;
app.listen(port, function() {
console.log("Listening on " + port);
All that said was Hello World so I created index.html and changed web.js to this.
var express = require('express');
var fs = require('fs');
var htmlfile = "index.html";
var app = express(express.logger());
app.get('/', function(request, response) {
var html = fs.readFileSync(htmlfile).toString();
response.send(html);
});
var port = process.env.PORT || 8080;
app.listen(port, function() {
console.log("Listening on " + port);
Now that serves index.html instead, but how do I get /blog or /archive to work?
You can add other routes to your code to handle specific URL formats. Make sure the more specific URLs are listed before the general route (/ or *)
// Handle request for blog
app.get('/blog', function(req, res){
res.send('A list of blog posts should go here');
});
// Handle request for archive
app.get('/archive', function(req, res){
res.send('Archive content should go here');
});
// Route for everything else.
app.get('*', function(req, res){
res.send('Hello World');
});
I've got a more lengthy explanation about this here: http://hectorcorrea.com/#/blog/introduction-to-node-js/51

Categories