On Replit, rendering the html file using res.sendFile inside a app.get works perfectly fine, AND I am able to add logos, styles, and js logic file by passing in express.static middleware.
BUT when I try to also include the html as a static file passed to express.static middleware, the page does not render.
Here's the replit: https://replit.com/#yanichik/NodeJSandExpressFullCourseFCC#02-express-tutorial/app.js
Renders as expected when html passed in with res.sendFile:
const express = require('express'); const path = require('path');
const app = express();
// setup static & middleware // static -> file that server does NOT
have to change app.use(express.static(path.resolve(__dirname,
'./public')))
app.get('/', (req, res) => { res.sendFile(path.resolve(__dirname,
'./navbar-app/index.html')) })
app.all('*', (req, res) => { res.status(404).send('Resource not
found.') })
app.listen(5000, () => { console.log('Server listening on port
5000...') })
module.exports = app;
Now, DOES NOT render as expected when html passed in with express.static middleware:
const express = require('express'); const path = require('path');
const app = express();
// setup static & middleware // static -> file that server does NOT
have to change app.use(express.static(path.resolve(__dirname,
'./public')))
// app.get('/', (req, res) => { //
res.sendFile(path.resolve(__dirname, './navbar-app/index.html')) // })
app.all('*', (req, res) => { res.status(404).send('Resource not
found.') })
app.listen(5000, () => { console.log('Server listening on port
5000...') })
module.exports = app;
You have to specifically request for the statically exposed files like so:
https://baseURL.com/navbar-app/index.html
When you comment out get routes.
If you have your get route uncomented route then
https://baseurl.com
Will return the html file
Related
When I got to http://localhost:8090/ or http://localhost:8090/about my static files work.
But if I visit any of the posts for example http://localhost:8090/posts/lorem-ipsum I get GET error in browser console. ( tried to server file from path http://localhost:8090/posts/css/style.css )
Server.js
`
app.use(express.static(path.join(__dirname, "ShowAnime")))
app.use('/', require(__dirname + "/ShowAnime/route.js"))
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
console.log(__dirname, path)
})
`
routes
`
router.get(['/', '/home'], (req, res) => {
res.sendFile(path.join(__dirname, "index.html"))
})
router.get(['/watch', '/watch/:slug'],
(req, res) => {
res.sendFile(path.join(__dirname, "Video.html"))
})
module.exports = router
`
the path of the static files seem to change on using slugs
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});
});
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.
Im new at nodejs programming and im having a little problem now. When i try to go localhost:3000/ i want to go homeController and index function prints the HTML file.
APP.JS
const express = require('express')
const mongoose = require('mongoose')
const mongodb = require('mongodb')
const app = express();
const homeController = require('./home/homeController.js');
app.get('/', function(req, res) {
res.redirect(homeController.index);
});
app.listen(3000, () => console.log('Example app listening on port 80!'))
HOMECONTROLLER.JS
var path = require("path");
exports.index = function(req, res){
res.sendFile(path.join(__dirname+'/index.html'));
};
console.log('test33');
Also i am using exports to seperate app.js from other controllers. Is this the right way? I have a history with Python Django framework and we used to use URLs to navigate our program.
Thanks.
OUTPUT
Cannot GET
/function%20(req,%20res)%7B%0A%20%20res.sendFile(path.join(__dirname+'/index.html'));%0A%7D
Your problem is that homeController.index is a function, but you're not calling it. Replace:
app.get('/', function(req, res) {
res.redirect(homeController.index);
});
with:
app.get('/', homeController.index);
Your homeController.js exports an index function which requires two parameters reqand res.
So you have to update your app.js accordingly :
app.get('/', function(req, res) {
homeController.index(req, res);
});
edit: by the way, your app is listening to port 3000
I want to export my routes in external files.
Everything but the root route is working:
localhost/login -> "Login page"
localhost/ -> empty
server.js:
// SET UP =============
var express = require("express");
var app = express();
var port = 80;
var bodyParser = require("body-parser");
// CONFIG =============
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.urlencoded({'extended':'true'}));
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
// ROUTES =============
var base = require("./routes/base");
app.use("/",base);
// LISTEN =============
app.listen(port);
console.log("Server listening on port " + port);
base.js:
var express = require('express')
var router = express.Router()
//Home
router.get('/', function (req, res) {
res.send('Home page')
})
//Login
router.get('/login', function (req, res) {
res.send('Login page')
})
module.exports = router
You don't need to specify the route on app.use('/', base) instead just supply the router middleware directly to your express app and let the router within base handle the request.
app.use(base)
Uhm, okay I found my problem.
There is an empty index.html in my ./public folder.
You're overwriting the root route with your /login route and only exporting the /login one because of that. If you want to keep all routes in one file I recommend doing something in you base.js file like:
module.exports = function(server){
server.get('/', function(request, response){
response.send('Home page.');
});
server.get('/login', function(request, response){
response.send('Login page.');
});
}
Then in the server.js file import the route using:
require('./routes/base.js')(app);
This immediately imports the routes and calls their functionality on the Express server you crated :)