MERN deploy script bundles on render - node.js

All my code compiles into dist folder. Client by CopyWebpackPlugin, server by tsc. and it looks like this. HTML sends app.get("*", (req, res) => { res.sendFile(path.join(__dirname, "client", "public", "index.html")); }); For static files i tried app.use("/static", express.static(path.join(__dirname, "client"))); app.use(express.static(path.join(__dirname, "client", "public"))); etc. Add all variants of scripts connection
<!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" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet" />
<title>Document</title>
</head>
<body>
<div id="root"></div>
<script src="/bundle.js"></script>
<script src="/client/public/bundle.js"></script>
<script src="/static/bundle.js"></script>
<script src="/static/public/bundle.js"></script>
</body>
</html>
And all my bundle.js files looks like this deployed app. How i suppose to add script bundles? Repo https://github.com/Dimkosyanklg/Cards-Test
Can't figure it out

Related

CSS and JS file not linking in node js

I want to use middleware func to serve static file,but the problem is that my css file is not linking with html file using node and express
error is:
Refused to apply style from 'http://localhost:4000/static/css/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
app.js:
const express=require('express');
const path=require('path');
const app=express();
app.use('/public',express.static(path.join(__dirname,'static')));
app.get('/',(req,res)=>{
res.sendFile(path.join(__dirname,'static','index.html'));
});
app.listen(3000);
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="/static/css/style.css">
</head>
<body>
<div class="asd">
Hi xyz here..
</div>
<script src="/static/js/script.js"></script>
</body>
</html>
folder structure is:
static
css
main.css
js
script.js
index.html
app.js
I tried a lot , but i am not able to find the error,
please help!!
Thanks!!
We will have to do something like that:
app.js
const express=require('express');
const path=require('path');
const app=express();
app.use('/public', express.static(path.join(__dirname,'./static')));
app.get('/',(req,res)=>{
res.sendFile(path.join(__dirname,'static','index.html'));
});
app.listen(3000, () => {
console.log("Starting at", 3000);
});
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="/public/js/main.js"></script>
<link rel="stylesheet" href="/public/css/style.css">
</head>
<body>
<div class="asd">
Hi xyz here..
</div>
<script src="/public/js/script.js"></script>
</body>
</html>
Here is the screenshot:
A basic thumbs rule we can think of:
app.use('<something_here>', express.static(path.join(__dirname,'./static')));
<link rel="stylesheet" href="<something_here>/css/style.css">
<link rel="stylesheet" href="<something_here>/css/style.css">
You don't need to add '/' in the path:
<link rel="stylesheet" type="text/css" href="css/style.css">
Also, you should make a change in your app file:
app.use(express.static(__dirname + '/static'));
This way express knows from where it has to serve the static files.
You are serving the static folder at /public endpoint. So you should change the link to
<link rel="stylesheet" type="text/css" href="/public/css/style.css">
and
<script src="/public/js/script.js"></script>
Also check the name of the css file.

Favicon with webpack and vue-cli

Hey everyone so I have a predicament. index.html is created by webpack for my vue project. It's currently looking for favicons inside the the dist folder as shown below. However the icons folder does not even exist inside of the dist/img folder. I didn't configure webpack I am just managing the site and honestly don't know that much about it. I don't know how I would put those files in the dist folder and have it stick as it is in the .gitignore file and I am pretty sure they don't want me messing with that. How can I get those files in a place they will be picked up by webpack or edit webpack to look for the files in a different location?
<!DOCTYPE html>
<html>
<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>Vue App</title>
<link href="/bundle.js" rel="preload" as="script" />
<meta
name="viewport"
content="width=device-width,initial-scale=1,user-scalable=no"
/>
<link
rel="icon"
type="image/png"
sizes="32x32"
href="/img/icons/favicon-32x32.png"
/>
<link
rel="icon"
type="image/png"
sizes="16x16"
href="/img/icons/favicon-16x16.png"
/>
<link rel="manifest" href="/manifest.json" />
<meta name="theme-color" content="#4DBA87" />
<meta name="apple-mobile-web-app-capable" content="no" />
<meta name="apple-mobile-web-app-status-bar-style" content="default" />
<meta name="apple-mobile-web-app-title" content="creative-engine-spa" />
<link
rel="apple-touch-icon"
href="/img/icons/apple-touch-icon-152x152.png"
/>
<link
rel="mask-icon"
href="/img/icons/safari-pinned-tab.svg"
color="#4DBA87"
/>
<meta
name="msapplication-TileImage"
content="/img/icons/msapplication-icon-144x144.png"
/>
<meta name="msapplication-TileColor" content="#000000" />
</head>
<body>
<div id="app"></div>
<script type="text/javascript" src="/bundle.js"></script>
</body>
</html>
I don't know if this would help ya'all with my question but I also have this code in my vue.config.js file
const path = require("path");
module.exports = {
chainWebpack: config => {
config;
config.plugin("html").tap(args => {
args[0].meta = {
viewport: "width=device-width,initial-scale=1,user-scalable=no"
};
return args;
});
},
configureWebpack: {
devtool: "cheap-source-map",
output: {
filename: "bundle.js"
}
}
};
you can define the path of the favicon in vue.config.js file
Read for more info here
const path = require("path");
module.exports = {
chainWebpack: config => {
config;
config.plugin("html").tap(args => {
args[0].meta = {
viewport: "width=device-width,initial-scale=1,user-scalable=no"
};
args[0].inject = true;
args[0].filename = "index.html";
args[0].favicon = "./public/favicon.ico"; // path to favicon
return args;
});
},
configureWebpack: {
devtool: "cheap-source-map",
output: {
filename: "bundle.js"
}
}
};
I had to find my static folder. In my case it was the public folder and drop the files in there. In the folder structure I wanted to grab them in. Apparently your static folder gets built every time. In my case my folder structure looked like so public/img/favicon-32x32.png

router.post is not rendering a page

I am learning node. I am stuck where I can render a view from get method but not from post.
app.js
var express = require("express");
var path = require("path");
var favicon = require("serve-favicon");
var logger = require("morgan");
var cookieParser = require("cookie-parser");
var bodyParser = require("body-parser");
var test = require("./routes/test");
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");
app.use(test);
test.js
var express = require("express");
var router = express.Router();
router.get("/test", function(req, res, next) {
res.render("testView1"); //working OK
});
router.post("/test", function(req, res, next) {
console.log("Its a test") // Working OK
res.render("testView2",{
// some data to be posted
}); // not redirecting to testView2
});
module.exports = router;
post /test is to be called on a button click event. it should render testView2 page where I have to display some data. I am stuck with this rendering kind of thing......Please help me to learn this.
Thanks,
Sunil
testView2.ejs is just a simple plain html template as of now
testView2.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title></title>
</head>
<body>
<h1>testview 2</h1>
</body>
</html>
testView1.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title></title>
<% include ./scriptLinks/headerLinks.ejs %>
</head>
<body>
<h1>TestView 1</h1>
<button id="btn-test">Test</button>
<script>
$("#btn-test").on("click", function(e) {
e.preventDefault();
$.post("/test", { name: " some data" });
});
</script>
</body>
</html>
and yes All ejs files are in view folder.
Thank you.
Of course it will not work. $.post is ajax request + it's asynchronous so it will not make browser navigate to /test route with post method in header.
Make testView1.ejs have such content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title></title>
<% include ./scriptLinks/headerLinks.ejs %>
</head>
<body>
<h1>TestView 1</h1>
<form method="post" action="/test">
<button id="btn-test">Test</button>
</form>
</body>
</html>
but if You insist on ajax call - so do this:
1) testView2.ejs must consist of only this (no headers, no body, no html tags):
<h1>testview 2</h1>
2) testView1.ejs :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title></title>
<% include ./scriptLinks/headerLinks.ejs %>
</head>
<body>
<h1>TestView 1</h1>
<form method="post" action="/test">
<button id="btn-test">Test</button>
</form>
<script>
$(function() {
$("from").on('submit', function(e) {
e.preventDefault();
var method = $[$(this).attr('method').toLowerCase()];
if (!method) method = 'get';
method(
$(this).attr('action'),
{ name: " some data" },
function(response) {
$('body').html(response);
});
});
});
</script>
</body>
</html>
warning: I don't recommend to inject html response to body - it may lead to unexpected behavior, since You don't seem to have enough frontend experience

EJS/Node/Express - Having a header partial, how to change title for each page?

I recently took a course on back-end web developing.
As the title says, I don't get how can I use a header partial for the whole website but have different titles for each page. (because is included in the tag)
Is there any trick?
1st) In your Express route:
app.get("/", function(req, res){
res.locals.title = "Abel's Home Page"; // THIS LINE IS KEY
res.render("home.ejs");
});
2nd) In your views/home.ejs file:
<% include partials/header.ejs %>
3rd) In your views/partials/header.ejs file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title><%= title %></title> <!-- THIS LINE IS KEY -->
<link rel="stylesheet" href="../style.css">
<link rel="shortcut icon" href="../logo_sm.png" type="image/x-icon">
</head>
<body>
Each page that includes the partial is free to pass data to said partial through parameters. See here for an example.

Angular 6 | Express : Getting 404 error on dist files

Thanks for taking the time to read my question. My website works fine when I run ng serve. When I run ng build --prod, that works fine as well. Problem is, when I try to render index.html in dist im getting 404 errors. The errors are 404 errors for my main, styles, and polyfill files. I'm trying to build a back end so that I can process card payments. Any help would be appreciated - have been knocking my head against the wall for hours now with no resolve. This is my code below:
server.js
var express = require('express');
var app = express();
var server = require('http').Server(app);
var bodyParser = require('body-parser');
app.use(express.static(__dirname));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
server.listen(2000, function(){
console.log('Listening on 2000..')
});
console.log(__dirname);
app.get('/', (req, res) => {
res.sendFile(__dirname + '/dist/culture/index.html');
});
src/index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Culture</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.13/css/all.css" integrity="sha384-DNOHZ68U8hZfKXOrtjWvjxusGo9WQnrNx2sqG0tfsghAvtVlRW3tvkXWZh58N9jp" crossorigin="anonymous">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
</head>
<body>
<app-root></app-root>
</body>
</html>
dist/index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Culture</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.13/css/all.css" integrity="sha384-DNOHZ68U8hZfKXOrtjWvjxusGo9WQnrNx2sqG0tfsghAvtVlRW3tvkXWZh58N9jp" crossorigin="anonymous">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<link rel="stylesheet" href="styles.aaf8a2468e47be90b64b.css"></head>
<body>
<app-root></app-root>
<script type="text/javascript" src="runtime.a66f828dca56eeb90e02.js"></script><script type="text/javascript" src="polyfills.b4daf421c94934f530d4.js"></script><script type="text/javascript" src="main.36d7357da7cc32c08c65.js"></script></body>
</html>
Again, in short, localhost is giving 200 code which is good it means its connecting to the right place. The problem is once it is connected it can not find any files. What am I doing wrong? Thanks
You must correct this line of code: app.use(express.static(__dirname)); to something like this: app.use(express.static(path.join(__dirname, 'dist/culture'))); if your Angular app files are in dist/culture directory.
Main problem is that when your index.html for example tries to load <link rel="icon" type="image/x-icon" href="favicon.ico"> it uses request to path http://localhost:2000/favicon.ico. Your express backend have defined static assets on __dirname and your actual app is in dist/culture so your request should look like http://localhost:2000/dist/culture/favicon.ico.
Applied change has improved configuration of static files location.

Resources