CSS file is not connecting in an express app - javascript

When running my app.js file
const express = require('express');
const path = require('path');
const app = express();
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'))
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '/index.html'));
});
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`Serving on port ${port}`)
})
this is my index.html file is
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="styles.css" type="text/css" />
</head>
<body>
<h1> Testing CSS</h1>
</body>
</html>
then I can not observe the changes of CSS file on the page. But when I open the HTML file with live serever I can see the CSS changes why is this happening.
When I am running my app.js file css is not connecting. But when I open the HTML file with live server CSS file is connecting. What is the reason behind this ??

app.use(express.static(path.join(__dirname, 'public')));
include this in your app.js create a folder called public and put the style.css in your public directory.
your code would be
const express = require('express');
const path = require('path');
const app = express();
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'))
app.use(express.static(path.join(__dirname, 'public'))); //<-here
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '/index.html'));
});
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`Serving on port ${port}`)
})

Related

applying styling for markdown in express/nodejs

I'm trying to load a markdown file as a static file which should afterwards be rendered via a html file. My question now is how I am to apply CSS Styling. Here is my code for the index.js:
const express = require('express');
const bodyparser = require('body-parser');
const showdown = require('showdown');
const marked = require('marked');
const app = express()
app.use(express.static(__dirname + '/'));
app.use(bodyparser.urlencoded({extend:true}));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.set('views', __dirname);
app.use(express.static('public'));
app.get('/article', (req,res)=> {
var markdown = require("markdown-js");
var fs = require("fs");
var path = __dirname+'articles/article.md'
app.use(express.static("public"));
fs.readFile(path, 'utf8', function(err, data) {
if(err) {
console.log(err);
}
//res.send(marked("" + data));
//console.log(result);
res.render('index.html');
});
});
// listen to port
const PORT= 3000;
app.listen(process.env.PORT || 3000, function(){
console.log('server is running on port 3000');
})
The code for my current html file looks the following such that index.html:
<!DOCTYPE html>
<html lang="en">
<script src="style.css"></script>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<% result %>
</body>
</html>
In order to use variables you have to use ejs you can read about it here https://ejs.co/
then you can do something like this:
First change the name to index.ejs
Then you have to pass the data
res.render("index", { result: data })

I have an css 404 error with my website but the css exsits

I have question with express
server.js
const express = require('express')
const app = express()
const port = 8080
app.use(express.static('public'))
app.use('/css', express.static(__dirname + 'public/css'))
app.use('/js', express.static(__dirname + 'public/js'))
app.use('/img', express.static(__dirname + 'public/img'))
app.set('views', './views')
app.set('view engine', 'ejs')
app.get('/signin', (req, res) => {
res.render('signin')
})
app.listen(port, () => {
console.log('server is listening to port: 8080')
})
app.use(function(req, res, next) {
res.status(404);
// respond with html page
if (req.accepts('html')) {
res.end('404 - Not Found');
return;
}
// respond with json
if (req.accepts('json')) {
res.json({ error: 'Not found' });
return;
}
});
File structure
public
css
signin.css
img
js
views
signin.ejs
server.js
signin.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="../public/css/signin.css">
</head>
<body>
<h1>works</h1>
</body>
</html>
signin.css
body{
color: yellow;
}
and the error is
http://localhost:8080/public/css/signin.css [HTTP/1.1 404 Not Found 4ms]
Can someone help me?
What is the error
I can identify two issues.
First is that the code just concatenates __dirname + 'public/css'. The __dirname does not include a trailing slash, so if your path is /home/foo, you'll get a path like /home/foopublic/css. Use path.join() instead.
Second, the HTML appears to refer to the CSS file relative to the location of the HTML on your disk. As there is already a handler for the path /css set which serves files from the css directory on your disk, the correct path would be /css/signin.css instead of ../public/css/signin.css.
So, on the node.js side:
const path = require('path')
app.use('/css', express.static(path.join(__dirname, 'public/css')))
app.use('/js', express.static(path.join(__dirname, 'public/js')))
app.use('/img', express.static(path.join(__dirname, 'public/img')))
Although you don't really even need these, as there app.use(express.static('public')) middleware already serves the files and directories from the public directory.
And the HTML:
<link rel="stylesheet" href="/css/signin.css">

Sending data object to another page using nodeJS and EJS

SI have an express server running. In the app.post ('/ login'), I have a data object that has a name and a password which i obtained from a form. I would like to forward this data to another EJS page.
app.js --> server
const express = require('express');
const app = express();
const port = 3000 || process.env.PORT;
app.use(express.json());
//Set the views + engine
app.set('views', './views');
app.set('view engine', 'ejs');
app.get('/', (req, res) => {
res.render('index');
});
app.get('/about', (req, res) => {
res.render('about');
});
app.post('/login', (req, res) => {
const data = req.body;
res.render('about', {data: data}); //i want to send this data to the about page and priew it on the screen
});
app.listen(port, () => {
console.log(`Listening on port: ${port}`);
})
about.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Data</h1>
<p><%= data %></p> <!--Preview to entred data from the user here-->
</body>
</html>

How to refer a css file from index.html in React

I have a folder called assets which have a styles.css and then I have index.html which I would want to reference styles.css but for some reason it can't.
My current solution is this:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>My App</title>
<link rel="stylesheet" href="/styles.css">
</head>
<body>
<div id="app"></div>
<script type="text/javascript" src="/bundle.js"></script>
</body>
</html>
And I have the node server running like this:
var webpack = require("webpack");
var config = require("./webpack.config.js");
var http = require('http');
var express = require('express');
var app = express();
var proxy = require('http-proxy-middleware');
var path = require('path');
const compiler = webpack(config);
app.use(require("webpack-dev-middleware")(compiler, {
noInfo: true,
publicPath: "/"
}));
app.use(require("webpack-hot-middleware")(compiler));
app.use('/auth', proxy('http://localhost:8081', {changeOrigin: true}));
app.use('/api', proxy('http://localhost:8081', {changeOrigin: true}));
app.get("*", function(req, res) {
res.sendFile(__dirname + '/index.html');
});
/**
* Anything in public can be accessed statically without
* this express router getting involved
*/
app.use(express.static(path.join(__dirname, 'assets'), {
dotfiles: 'ignore',
index: false
}));
var server = http.createServer(app);
server.listen(3000, function() {
console.log("express listening at localhost:3000");
});
This is not working for me it cannot find the css file, how can I make it so I can reference the css file from index.html. Also I have index.js on my src folder which is used as an entrance file for running the whole React App.
Add the route for styles.css before app.get("*",...)
app.get("/styles.css", function(req, res) {
res.sendFile(__dirname + '/styles.css');
});

"Error: No default engine was specified and no extension was provided" When trying to do Server Side Rendering in React

Hi I'm trying to do server-side rendering in my react app but I get the error
Error: No default engine was specified and no extension was provided.
I've got an ejs template index.ejs:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Hello Redux</title>
<link href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/cyborg/bootstrap.min.css" rel="stylesheet" integrity="sha384-D9XILkoivXN+bcvB2kSOowkIvIcBbNdoDQvfBNsxYAIieZbx8/SI4NeUvrRGCpDi" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="app"><%- myHtml -%></div>
<script src="bundle.js"></script>
</body>
</html>
A request handler function:
'use strict'
import axios from 'axios'
function handleRender(req, res){
axios.get('http://localhost:3001/books')
.then(function(response){
var myHtml = JSON.stringify(response.data);
res.render('index', { myHtml })
})
.catch(function(err){
console.log('#Initial Server-side rendering error', err);
})
}
module.exports = handleRender;
And in app.js I require the request handler function and set it:
app.set('view engine', 'ejs');
app.use(requestHandler);
Can anyone help me with this issue? The link to my github repo with all the code is at https://github.com/edward-hong/book-shop
in app.js
var app = express();
app.use(logger('dev'));
var apiProxy = httpProxy.createProxyServer({
target: 'http://localhost:3001'
});
app.use('/api', function(req, res){
apiProxy.web(req,res)
})
app.use(express.static(path.join(__dirname, 'public')));
app.set('view engine', 'ejs');
just move app.set('view engine', 'ejs') and put it right after var app = express()
apiServer.js is your entry, so you need to explicitly app.set('view engine', 'ejs') there

Categories