Here is my express code:
const express = require('express');
const serveStatic = require('serve-static');
const path = require('path');
// create the express app
const app = express();
var cors = require('cors');
app.use(cors());
app.use("/",serveStatic ( path.join (__dirname, '/dist') ) );
app.use('/static', express.static(path.join(__dirname, '/dist23')));
app.listen(port, () => {
console.log("listening on "+port)
});
The above code only works for the folder /dist. But when I go to /static, it shows a blank page and this error in the console:
If I put the js files from /dist23 into /dist, then /static works and shows me the application. Its almost like it is looking for files inside /dist and not /dist23. How do I fix it?
Both apps were built using vue-2.6.11. Both directories have files built/bundled for production.
You need to set the content type while serving your static files.
app.get('/index.html', (req, res) => {
res.set('content-type', 'text/plain').sendFile('index.html', { root: path.join(__dirname, 'public/dist/') })
});
app.get('/', (req, res) => {
res.set('content-type', 'text/plain').sendFile('index.html', { root: path.join(__dirname, 'public/dist/') })
});
Related
Hope Youre all are doing Great,Im new in Expressjs and doing a project in it.
Actually I m getting problem to render a file that is place inside the a folder named as index.hbs in views directory,
When I try to access a found this error :
Error: Failed to lookup view "/blogger_dasboard" in views directory "C:\Users\HBK1007\Desktop\ExpressjsFyPEPakTourisum\template\views"
Im attaching folder structure images and my code as well
Here is the codeenter image description here
`
const express = require("express")
const app = express()
const path = require('path')
const port = 8000;
const hbs =require('hbs')
const bcrypt =require("bcryptjs")
// establishing db connection
require('./db/db_connec');
// Getting the collection of DB
const Registration=require('./models/registrationdb')
const NewsletterSubsciber=require('./models/newsletter')
const ContactUs_Client =require("./models/contactus")
// this is for DB data conersions
app.use(express.json());
app.use(express.urlencoded({extended:false}))
//public static port
const static_path = path.join(__dirname, '../public')
const tempalte_path = path.join(__dirname, '../template/views')
const bloggerdashboard_path = path.join(__dirname, '../template/views/blogger_dashboard')
const partials_path =path.join(__dirname,'../template/particles')
app.set('view engine', 'hbs');
app.set('views', tempalte_path)
hbs.registerPartials(partials_path)
app.use(express.static(static_path))
// BloggerDashboard Routes
app.get('/blogger_dashboard', (req, res) => {
res.render('/blogger_dasboard')
})
app.listen(port, () => {
console.log("Listning to portss ")
})
I mirrored your project and You have few errors:
Wrong paths, too many by one dot in : static_path, tempalte_path, bloggerdashboard_path, partials_path.
Insted of res.render("/blogger_dasboard") like that: res.render("blogger_dashboard"); Without slash and you missed h letter.
Working example below without static_path bcrypt and db (for obvious reasons)..
const express = require("express");
const app = express();
const path = require("path");
const port = 8000;
const hbs = require("hbs");
// const bcrypt = require("bcryptjs");
// establishing db connection
// require("./db/db_connec");
// Getting the collection of DB
// const Registration = require("./models/registrationdb");
// const NewsletterSubsciber = require("./models/newsletter");
// const ContactUs_Client = require("./models/contactus");
// this is for DB data conersions
// app.use(express.json());
app.use(express.urlencoded({ extended: false }));
//public static port
// const static_path = path.join(__dirname, "./public");
const tempalte_path = path.join(__dirname, "./template/views");
const bloggerdashboard_path = path.join(
__dirname,
"./template/views/blogger_dashboard.hbs"
);
const partials_path = path.join(__dirname, "./template/particles");
app.set("view engine", "hbs");
app.set("views", tempalte_path);
hbs.registerPartials(partials_path);
// app.use(express.static(static_path));
// BloggerDashboard Routes
app.get("/blogger_dashboard", (req, res) => {
res.render("blogger_dashboard");
});
app.listen(port, () => {
console.log(`Server is listening at http://localhost:${port}`);
});
My Project folder and file structure:
I have a index.js file with the following code...
const express = require('express');
const app = express();
app.use(express.json({ extended: false }));
app.use('/api/users/', require('./users/routes'));
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server started on PORT ${PORT}`));
and a routes.js file with the following code...
const express = require('express');
const router = express.Router();
router.get('test', (req, res) => {
console.log('im here!')
res.send('hello from test route!');
});
module.exports = router;
my file structure is...
server/
users/
routes.js
index.js
I am able to start the server with no issues, however, if I try to go to the route /api/users/test it does not work and says cannot get that route.
For some reason when I am creating files with the .js extension a .jsx icon comes up. I am using vscode and feel that this might be the issue but I don't know how to fix it?
As an update in my routes file...
router.get('test', (req, res) => {});
needs to change to the following...
router.get('/test', (req, res) => {});
and in my index.js file
app.use('/api/users', require('./users/routes'));
basically, adding the slash before the test and taking away the slash after users.
I do not know why that would be an issue but it now works.
In routes.js:
router
.get ('/test',(req, res) => {
console.log('im here!')
res.send('hello from test route!');
});
You just forgot the slash in front of your route.
You should now see your response # http://localhost:5000/api/users/test.
Hey guys so I have the following in my app.js file
const express = require("express");
const app = express();
const path = require('path');
const hbs = require("express-handlebars");
app.engine(
"hbs",
hbs({
extname: "hbs",
//defaultLayout: "layout",
layoutsDir: __dirname + "/views/layouts/"
})
);
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "hbs");
I also have a file located in server/views/layouts/ that is a handle bars file called share.hbs
I also have a file in my server/api/media.js that looks like this
const express = require("express");
const router = express.Router();
const database = require("../db");
router.get("/share", async (req, res, next) => {
res.render("share");
});
But when ever I try to render the file it errors out with the following error
Had to move my file out of the layouts folder and add this to the res.render call
res.render("share.hbs", { layout: "share" });
I'm prototyping a NextJS implementation with the following server code:
import express from 'express';
import next from 'next';
import path from 'path';
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
dotenv.config();
app.prepare().then(() => {
const server = express();
// Custom build resources aliases
// ---------------------------------------------------------------------
server.use('/favicon.ico', express.static(path.join(__dirname, 'static', 'images', 'icons', 'favicon.ico')));
// ---------------------------------------------------------------------
// Custom/dynamic routes
// ---------------------------------------------------------------------
server.get('/p/:id', (req, res) => {
const actualPage = '/post';
const queryParams = { title: req.params.id };
app.render(req, res, actualPage, queryParams);
});
// ---------------------------------------------------------------------
// Default route
// ---------------------------------------------------------------------
server.get('*', (req, res) => handle(req, res));
// ---------------------------------------------------------------------
// Express: Listener
server.listen(process.env.WEB_PORT, () => {
console.log(`Server listening on port: ${process.env.WEB_PORT}...`);
});
}).catch((ex) => {
console.error(ex.stack);
process.exit(1);
});
As apparent, my static assets sit in a /static/ folder. Of these, I have a favicon file at /static/images/icons/favicon.ico. I am able to visit this file using https://schandillia.com/static/images/icons/favicon.ico. However, when I try hitting https://schandillia.com/favicon, it throws a 404. Am I not using express.static() correctly?
I'm using express to serve files and everything is working but I can't get my console.log statement to show in app.get() route statment. I'm currently using app.use(express.static("public")); to serve from the public folder.
Here is the full code:
//Server static files from the public folder.
app.use(express.static("public"));
app.listen(PORT, function(){
console.log("Sever is running and listening on port: " +PORT);
});
//Establish routes
app.get('/', function (req, res) {
//res.sendFile('/student-profile');
res.send("This is the response.");
});
1) How can I get this work?
2) Also, is the index.html the first file that is looked for when serving static files from the public folder?
/* directories
public
views
app.js
*/
// create server
const express = require('express');
const app = express();
// import path
const path = require('path');
// use static directory
app.use(express.static(path.join(__dirname, 'public')));
app.get("/", (req, res, next) => {
res.send("This is the response.")
// if you want to render a template then
// in the {} you can send data with
//res.render("FileName", {})
})
app.listen(PORT, () => {
console.log("Sever is running and listening on port: " +PORT);
});