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
Related
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
I am creating a static site, (HTML, CSS, JS) using nodeJS and express for the server...
I am trying to create routes, so that the user sees /about, as opposed to about.html...
For the main, home page (home.html), it works fine. However, when trying to access the pages using the defined routes via app.get, I keep getting errors - any pointers...
Code is as follows - my styling and JS files ate in the public directory and the HTML files are in the views directory :
const express = require('express');
const app = express();
const path = require('path');
app.use(express.static(path.join(__dirname + '/public')));
app.use(express.static(path.join(__dirname + '/views')));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/views/home.html');
});
app.get('/about', (req, res) => {
res.sendFile(__dirname + '/views/about.html');
});
app.get('/contact', (req, res) => {
res.sendFile(__dirname + '/views/contact.html');
});
// app.use(express.static('public'));
// app.use(express.static('views'));
// console.log(__dirname);
module.exports = app;
The error I get is :
Cannot GET /views/contact.html
if your foldering is like the following photo you can do like this:
app.get('/about', (req, res) => {
res.sendFile(__dirname + '/views/about.html');
});
app.get('/contact', (req, res) => {
res.sendFile(__dirname + '/views/contact.html');
});
app.get('/', (req, res) => {
res.sendFile(__dirname + '/views/home.html');
});
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.
This is my index.js file:
const express = require('express');
const mongoose = require('mongoose');
const Post = require('./models/Post');
const keys = require('./config/keys');
const path = require('path');
mongoose.connect(keys.mongoURI);
const app = express();
app.use(express.static(path.join(__dirname, '../react-app/build')));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '../react-app/build',
'index.html'));
});
app.get('/posts', (req, res) => {
Post.find({}, (err, posts) => {
if(err) {
console.log(err);
res.sendStatus(500);
} else {
res.send(posts)
}
})
});
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`App listening on port ${PORT}`));
I've builded my react frontend to the location specified in the path.join. However, if I use the app.use(express.static(...)), if I use any path at all, it will always return index.html from my build.
I'd like to see the posts object when I got to '/posts' endpoint, but it doesn't work and I can't get the build serving working without express static.
EDIT:
I tried console logging inside '/' handler, but it logged nothing either. I got everything working when I remove the app.use line entirely. Some tutorials use this approach, why is not working?
So try this:
const express = require('express');
const mongoose = require('mongoose');
const Post = require('./models/Post');
const keys = require('./config/keys');
const path = require('path');
mongoose.connect(keys.mongoURI);
const app = express();
app.use(express.static(path.join(__dirname, '../react-app/build')));
app.get('/posts', (req, res) => {
Post.find({}, (err, posts) => {
if(err) {
console.log(err);
res.sendStatus(500);
} else {
res.send(posts)
}
})
});
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '../react-app/build',
'index.html'));
});
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`App listening on port ${PORT}`));