so I have a very basic file structure going but for whatever reason I cannot get the css to show up in the project when I run it on the localhost. everything else except the css loads here's the structure
enter image description here
I have tried all kinds of path files and have just resorted to straight up copying the entire file path into the relevant parts but still that does not work. I am calling everything from the index.js file.
here's the code for that
const path = require('path');
const express = require('express');
const hbs = require('hbs')
const app = express();
const config = require('./config/request');
const publicDirectoryPath = path.join(__dirname, 'public')
// it was ../public but that did nothing
// also ./public/
// also ../public/
// also /public/
// also public/
const viewsPath = path.join(__dirname, './templates/views')
const partialsPath = path.join(__dirname, './templates/partials')
// error handler
app.use(function(req, res, next) {
if(config.MARKETPLACE_ID === '' || config.SECRET === '') {
res.send('MarketplaceId and secret must be set with your marketplace API credentials');
} else{
next();
}
});
app.set('view engine', 'hbs')
app.set('views', viewsPath)
hbs.registerPartials(partialsPath)
app.use(express.static(publicDirectoryPath))
app.get('', (req, res) => {
res.render('index')
})
app.listen(process.env.PORT || 3000, function(err, req, res) {
if(err) {
res.send('There was no endpoint listening');
} else{
console.log('server started on port: ', (process.env.PORT || 3000));
}
});
css file (it's VERY, VERY complicated so take your time reading through it)
.main-content {
background-color: purple;
}
index.hbs file
<!DOCTYPE html>
<html>
<head>
<title>marketplace</title>
<link rel="stylesheet" src="/literally/the/file/path/I copied/from visual studio code/public/css/styles.css" >
I even put the file into the terminal to get the exact address cause I was convinced I was spelling something wrong
unless all the possible tools used to determine file path on my Mac are wrong then this is the correct file path.
</head>
<body>
<div class="main-content">
so yeah. the index.hbs page should have a purple background. it used to say something about there being an error loading the css file cause of the MIME type or something but I've basically played around with it and got that to go away. now there is no background. no css loaded. and nothing in the console about an error or file not loading. so what gives?
at one point I was trying all of these to load in my css
<link rel="stylesheet" type="text/css" src="actual path copied from the terminal the path is 100% correct>
<link rel="stylesheet type="text/css" href="100% correct file path">
I had the same issue, so solve it you should put in the link src only "/css/styles.css".
<link rel="stylesheet" href="/css/style.css">
I hope it works for you as well.
Related
I want to create a website with html/css/javascript for the frontend and c++ for the backend. (The c++ file is supposed to calculate the distance between two nodes on a map, created with leaflet.) Both, the html and the c++ file are finished I "just" need to connect them somehow.
I tried to create a http webserver with node.js by the help of this post.
My problem now is: the link for leaflet (javascript and css) that I have to include in my index.html file doesn't work / the map won't show on the website.
Is there a way to workaround this problem?
My index.html file contains this:
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.9.3/dist/leaflet.css" integrity="sha256-kLaT2GOSpHechhsozzB+flnD+zUyjE2LlfWPgU04xyI=" crossorigin="" />
<link rel="stylesheet" href="/static/main.css">
<script src="https://unpkg.com/leaflet#1.9.3/dist/leaflet.js" integrity="sha256-WBkoXOwTeyKclOHuWtc+i2uENFpDZ9YPdf5Hf+D7ewM=" crossorigin=""></script>
<script src="/static/main.js" type="text/javascript"></script>
My server.js file contains this:
//Create server
const express = require('express');
const path = require('path');
const app = express();
app.use('/static', express.static('public'));
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, '/index.html'));
});
app.listen(3000);
I am trying to use node.js to run a html file. I already have a login.html and styles.css for for the login page but now I don't know how to use the node js file to run my login.html page. I follow this youtube tutorial to make the a login authentication. It seems to have everything needed but now I dont know how to use it in my login.html file.
I need help modifying this so that I can run my login.html file.
index.js file
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const postRoute = require('./routes/posts');
//Import Routes
const authRoute = require('./routes/auth');
dotenv.config();
//Connect to DB
mongoose.connect(
process.env.DB_CONNECTION,
{ useNewUrlParser: true, useUnifiedTopology: true },
() => console.log('Connected to DB')
);
//Middleware
app.use(express.json());
//Routes Middlewares
app.use('/api/user', authRoute);
app.use('/api/posts', postRoute);
// start listening
app.listen(3000, () => console.log('Server up and running port:3000'));
I am new to node.js and am completely lost on how to solve this problem.
you can solve it in two ways, first you can install view engine like ejs and use res.render (if you want more about it i can explain)
Second you can response with the HTML file like this: (works only with express and you have express)
app.get('/yourRotue', function(req, res, next){
res.sendFile(__dirname + '/yourPath/htmlFile.html');
});
How to use EJS (basic):
First please install EJS with npm install ejs install body parser npm install body-parser
now you need to create two folders on the root folder, public and views.
inside views you can create a folder auth and put your EJS files there.
then on your app.js (or index.js, the main file) add view engine middleware:
(*notice that you dont need to require ejs, also notice you dont need to install path its built in with node)
//import body parser on top (to parse json/urlencoded/text..
const bodyParser = require('body-parser');
//import path so you can use it for the public folder
const path = require('path');
//this line makes public folder public so you can store js/css/image...
app.use(express.static(path.join(__dirname, 'public')));
//use the body parser as middleware
app.use(bodyParser.json({ limit: '200mb' }));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.text({ limit: '200mb' }));
//this line tells node js to use ejs
app.set('view engine', 'ejs');
//this line make sure that the views folder is the folder with the ejs files
app.set('views', 'views');
//now your route will look like this:
app.get(/routeName, (req,res,next) => {
let example
//you return response with render, to render the file you want.
// you dont write the views folder name, only the file name without .ejs
// elso you can run functions here and later send the response to the front end
function(){
example = 1 + 1 * 5
}
// *very often the function above is to find something in the db
return res.render('auth/ejsFileName', {
pageTitle: 'some page title for the example',
exampleKey: example
})
})
I can suggest you to use mvc (models, views, controllers) structor, if you want to know more about it you can open new question or to search about it.
EJS:
put your css and js in public folder, you can create js folder and css folder inside the public folder and then put the css in js in their folder.
*notice you dont need to write ./public in the route.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/css/someCssFile.css">
<!-- here is the title that comes from the back end -->
<title><%= pageTitle %></title>
</head>
<main>
<h1>Here you can see the example with the function<%= exampleKey %></h1>
</main>
<script src="/js/someJsFile.js"></script>
</body>
</html>
the file look like html but it has .ejs
there is many things you can do with ejs like to loop through values.. i would suggest to learn a bit more.
this is the basic it should work.
For the post request i need to know if you are posting a form as urlEncoded or json. so i can show you how it should look like.
You can try to use some template engines like Handlebars. https://youtu.be/1srD3Mdvf50 You can try to follow this tutorial in order to load some html from the server side. Then you can use different selectors in order to interact with DOM elementa
I've been trying to learn how to set up a node.js server for a simple website for the first time and am encountering some strange behavior. When I open my index.html file from my computer it opens up perfectly with all of the CSS working properly. However I then set up a basic node.js server and when accessing the index.html file through my browser it only loads the html but not the CSS.
I'm extremely new to this so haven't been able to try much, also because the code is extremely simple so can't see what's missing (I tried following this tutorial if that helps). I also found another question that seemed similar on here but it didn't have an answer and didn't really help, I did check that all the files are UTF-8.
The HTML:
<html>
<head>
<title>My Page</title>
<link rel="stylesheet" href="styles.css" type="text/css">
</head>
<body>
<h1>A headline</h1>
</body>
</html>
And the node.js server:
const http = require("http");
const fs = require("fs");
const server = http.createServer((req, res) => {
res.writeHead(200, {"Content-Type": "text/html"});
const myReadStream = fs.createReadStream(__dirname + "/index.html", "utf8");
myReadStream.pipe(res);
});
server.listen(3000, "127.0.0.1");
console.log("Listening to port 3000");
When I include the CSS within <style> tags and directly in index.html it does work, but I've tried putting <link rel="stylesheet" href="styles.css" type="text/css"> between <style> tags and that still doesn't (it would also be weird if that's necessary seeing as it displays perfectly when I simply open the html file). I've also tried removing type=text/css but that didn't seem to change anything. Any help would be much appreciated!
You need to serve the style.css as well. You are serving the index.html but in the index.html it is hitting http://127.0.0.1:300/style.css when the request is coming to your app it is STILL serving the index.html file. (You can confirm this in Network pane of developer tools)
const server = http.createServer(function (req, res) {
const url = req.url;
if (url === '/style.css') {
res.writeHead(200, { 'Content-Type': 'text/css' }); // http header
fs.createReadStream(__dirname + "/style.css", "utf8").pipe(res);
} else {
res.writeHead(200, { 'Content-Type': 'text/html' }); // http header
fs.createReadStream(__dirname + "/index.html", "utf8").pipe(res);
}
})
Note: It is very easy to achieve this using express, probably the most popular nodejs package.
The following is affecting my second html page model.html:
If my route address is with a '/ at the end (typed on browser addr field) like so: http://localhost:3002/home/model/ then the correct html page is loaded, but no css/js is loaded.
If my route address is without a '/ at the end like so: http://localhost:3002/home/model then the correct html page is loaded, and css/js is loaded.
Without '/' at the end, css/js loads fine using statics/css/style.css and js/dynamicData.js
The weird part is that when '/' is at the end, I can use ../statics/css/style.css to load the css and "../js/chartData.js" to load js - but that means the one without '/' now longer loads the css/js.
My folder structure:
js - has other js scripts
node_modules
statics
css - has style.css
image - has images
index.html
model.html
index.js - init express server
pc_server.js - express server
Express code (pc_server.js)
Middleware setup?:
process.chdir(__dirname);
// base = '/home'
app.use(base, express.static(__dirname));
Routes:
const INDEX_PAGE = '/';
const MODEL_PAGE = '/home/model';
function setupRoutes(app) {
const BASE = app.locals.base;
app.get(INDEX_PAGE, redirectHome(app));
// BASE = '/home'
app.get(BASE, toHomePage(app));
app.get(MODEL_PAGE, toModelPage(app));
Routes functions defined:
function redirectHome(app) {
return errorWrap(async function(req, res) {
try {
res.redirect(app.locals.base);
}
catch (err) {
console.error(err);
}
});
}
function toHomePage(app) {
return errorWrap(async function(req, res) {
try {
res.sendFile(path.join(__dirname+'/statics/index.html'));
}
catch (err) {
console.error(err);
}
});
}
function toModelPage(app) {
return errorWrap(async function(req, res) {
try {
res.sendFile(path.join(__dirname+'/statics/model.html'));
}
catch (err) {
console.error(err);
}
});
}
The goal is to load the same page with css/js with either http://localhost:3002/home/model/ or http://localhost:3002/home/model
Additional: Why is it that when I type http://localhost:3002/home I get http://localhost:3002/home/ automatically on my browser addr field?
the problem
it probably occurs due to relative links in your site.
when home/model is used - relative css/style.css link will lead to home/css/style.css
when home/model/ is used, the same link will lead to home/model/css/style.css
the solution:
the easiest way to solve it is changing your link tag to:
<link rel="stylesheet" type="text/css" href="../../home/statics/css/style.css">
this link goes to the root address, and then enters your path Independently from the user's path.
why it's working?
the ../../ prefix tell the browser to go two levels up.
the browser consider the "home/model/" as a visit inside a model folder inside home folder. two levels upward lead the browser to the root level, where it has a clean start.
when the user visits "home/model", it considered as a file inside the home folder. one level upward is the root level, and the second ../ does nothing.
after achieving the root level - the browser entering "home/statics/css/style.css" and find the right file in both cases :)
If I do a
res.sendfile('public/index1.html');
then I get a server console warning
express deprecated res.sendfile: Use res.sendFile instead
but it works fine on the client side.
But when I change it to
res.sendFile('public/index1.html');
I get an error
TypeError: path must be absolute or specify root to res.sendFile
and index1.html is not rendered.
I am unable to figure out what the absolute path is. I have public directory at the same level as server.js. I am doing the res.sendFile from with server.js. I have also declared app.use(express.static(path.join(__dirname, 'public')));
Adding my directory structure:
/Users/sj/test/
....app/
........models/
....public/
........index1.html
What is the absolute path to be specified here ?
I'm using Express 4.x.
The express.static middleware is separate from res.sendFile, so initializing it with an absolute path to your public directory won't do anything to res.sendFile. You need to use an absolute path directly with res.sendFile. There are two simple ways to do it:
res.sendFile(path.join(__dirname, '../public', 'index1.html'));
res.sendFile('index1.html', { root: path.join(__dirname, '../public') });
Note: __dirname returns the directory that the currently executing script is in. In your case, it looks like server.js is in app/. So, to get to public, you'll need back out one level first: ../public/index1.html.
Note: path is a built-in module that needs to be required for the above code to work: var path = require('path');
Just try this instead:
res.sendFile('public/index1.html' , { root : __dirname});
This worked for me.
the root:__dirname will take the address where server.js is in the above example and then to get to the index1.html ( in this case) the returned path is to get to the directory where public folder is.
An alternative that hasn't been listed yet that worked for me is simply using path.resolve with either separate strings or just one with the whole path:
// comma separated
app.get('/', function(req, res) {
res.sendFile( path.resolve('src', 'app', 'index.html') );
});
Or
// just one string with the path
app.get('/', function(req, res) {
res.sendFile( path.resolve('src/app/index.html') );
});
(Node v6.10.0)
Idea sourced from https://stackoverflow.com/a/14594282/6189078
res.sendFile( __dirname + "/public/" + "index1.html" );
where __dirname will manage the name of the directory that the currently executing script ( server.js ) resides in.
Based on the other answers, this is a simple example of how to accomplish the most common requirement:
const app = express()
app.use(express.static('public')) // relative path of client-side code
app.get('*', function(req, res) {
res.sendFile('index.html', { root: __dirname })
})
app.listen(process.env.PORT)
This also doubles as a simple way to respond with index.html on every request, because I'm using a star * to catch all files that weren't found in your static (public) directory; which is the most common use case for web-apps. Change to / to return the index only in the root path.
I tried this and it worked.
app.get('/', function (req, res) {
res.sendFile('public/index.html', { root: __dirname });
});
process.cwd() returns the absolute path of your project.
Then :
res.sendFile( `${process.cwd()}/public/index1.html` );
you can use send instead of sendFile so you wont face with error!
this works will help you!
fs.readFile('public/index1.html',(err,data)=>{
if(err){
consol.log(err);
}else {
res.setHeader('Content-Type', 'application/pdf');
for telling browser that your response is type of PDF
res.setHeader('Content-Disposition', 'attachment; filename='your_file_name_for_client.pdf');
if you want that file open immediately on the same page after user download it.write 'inline' instead attachment in above code.
res.send(data)
Another way to do this by writing less code.
app.use(express.static('public'));
app.get('/', function(req, res) {
res.sendFile('index.html');
});
If you want to set this up once and use it everywhere, just configure your own middleware. When you are setting up your app, use the following to define a new function on the response object:
app.use((req, res, next) => {
res.show = (name) => {
res.sendFile(`/public/${name}`, {root: __dirname});
};
next();
});
Then use it as follows:
app.get('/demo', (req, res) => {
res.show("index1.html");
});
I use Node.Js and had the same problem... I solved just adding a '/' in the beggining of every script and link to an css static file.
Before:
<link rel="stylesheet" href="assets/css/bootstrap/bootstrap.min.css">
After:
<link rel="stylesheet" href="/assets/css/bootstrap/bootstrap.min.css">
The following worked for me
res.sendFile(path.resolve(__dirname,'./path_to_file_from_current_directory'));
Worked for me:
res.sendFile("./public/filename.ext", { root: "./" });