router.post is not rendering a page - node.js

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

Related

MERN deploy script bundles on render

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

my req.body is empty when i try to get data from a form

I have a user route that render a form, now i wish to take data from the form using a post request, but when i attempt to do so, my req.body is {}. I've already tried using body parser but the result is the same one. I've also tried using the middleware of the encoded url in the app.js instead of the user routes, but that doesn't work ether.
const express = require('express');
const router = express.Router();
router.use(express.urlencoded({extended: true}));
const messages = [
{
text: "Hi there!",
user: "Amando",
added: new Date()
},
{
text: "Hello World!",
user: "Charles",
added: new Date()
}
]
router.get('/', (req, res) => {
res.render('index', {title: "Mini Messageboard", messages: messages});
});
router.get('/new', (req,res) => {
res.render('form')
})
router.post('/new', (req,res) => {
console.log(req.body) // {}
res.send(req.body)
})
module.exports = router;
my ejs file:
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="">
<meta name="keywords" content="">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel = "stylesheet" type = 'text/css' href="style.css">
<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:ital,wght#0,300;1,500&display=swap" rel="stylesheet">
<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=Poppins&display=swap" rel="stylesheet">
<title></title>
<body>
<form method="post" action="/new">
<input placeholder ="Insert your name here" type="text" name="" id="">
<input placeholder = 'Insert youre message here' type="text">
<button type="submit">Submit</button>
</form>
</body>
</html>
The name attribute is responsible for forming key-value pairs in the body of a request. Provide a name attribute for input tags, like:
<input type="text" name="*your key*"> and then in backend: console.log(req.body["*your key*"]) will give you the value of input tag.

Does Tailwind CSS work with express sendFile?

I am trying to send a html file through express but it is not able to include tailwindcss
I did all the set up correctly (at least that's what I think)
Is sendFile not capable of sending tailwindcss
This is the express setup
// express setup
const app = express();
const port = 9000;
app.use('/static', express.static('static'))
the endpoint
app.get("/", (req, res)=>{
res.sendFile(path.join(__dirname, "/template/home.html"))
});
html file
<!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>Website</title>
<link rel="stylesheet" href="../static/output.css" />
</head>
<body>
<h1 class="text-sm">Doesn't Works</h1>
</body>
</html>
css file
#tailwind base;
#tailwind components;
#tailwind utilities;
tailwind config file
module.exports = {
content: ["*"],
theme: {
extend: {},
},
plugins: [],
}
and yes the path are correct it works with normal css but not with tailwindcss
I also don't want to use pug for it
Is there a way around it?
You can simple Use the Play CDN to try Tailwind right in the browser without any build step.
Add the Play CDN script tag to the <head> of your HTML file, and
start using Tailwind’s utility classes to style your content.
But remember :
The Play CDN is designed for development purposes only, and is not the
best choice for production.
<script src="https://cdn.tailwindcss.com"></script>
Folder & file structure :
app.js
const express = require("express");
const path = require("path");
const app = express();
const port = 9000;
app.use(express.static("./public"));
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "/public/home.html"));
});
app.listen(port, () => {
console.log(`Server is listening at http://localhost:${port}`);
});
home.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://cdn.tailwindcss.com"></script>
<title>Express & TailwindCss</title>
</head>
<body>
<div class="flex items-center justify-center h-screen flex-col gap-5">
<h1 class="text-5xl font-bold underline text-green-500">
Express with TailwindCss
</h1>
<h3 class="text-blue-900 text-3xl font-bold">It does works! ;-)</h3>
</div>
</body>
</html>
Output :

how to pass automatic url to http protocol in Node js

In my file there is an index.html that contains the links, there is a display.html to render the images, a server.js and a folder containing the images.
When I click on the link, I want to open the display.html, but render a different image for each link. But I don't want to keep writing requests for each link.
<!DOCTYPE html>
<html lang="pt-br">
<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>Requisições</title>
<script src="funcoes.js"></script>
</head>
<body style="text-align: center;">
<h1 id="h1" style="font-size: 30px; color: #000;">Links</h1>
link 1
link 2
link 3
link 4
link 5
</body>
</html>
`
<!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>Display</title>
</head>
<body style="align-items: center; text-align: center;">
<div style="background-color: darkkhaki; width: 500px; height: 300px;">
<p>img</p>
</div>
</body>
</html>
const express = require('express')
const app = express();
app.use(express.static('.'))
const fetch = require('node-fetch')
app.get('/', (req, res)=>{
res.sendFile(__dirname+'/index.html')
})
app.get('/page/:1',(req, res)=>{
res.sendFile(__dirname+'/display.html')
} )
/*app.get('/page/:2',(req, res)=>{
res.sendFile(__dirname+'/display.html')
} )*/
app.listen(8080)
`How can I do this in the backend using Node and express?
Extract pageNumber from URL params by using req.params
This way you define a single route.
app.get('/page/:pageNumber',(req, res) => {
// Do something with the `pageNumber`
const { pageNumber } = req.params;
res.sendFile(__dirname + '/display.html')
});

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.

Resources