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 :
Related
Im trying to create server-side to my new React project.
I have some issue, when I send my HTML file using app.get , it renders the html file without the react component, so all I see is just a blank page.
im trying to render index.js.
this is my serverside code:
const express= require('express');
const path = require("path");
const app=express();
app.use(express.static('build'));
app.use(express.urlencoded({extended:false}));
app.get('*', function(req, res) {
res.sendFile(__dirname + '/build/index.html');
});
app.listen(3000,function(){
console.log("Server is on");
});
my index.js code:("App" is my main component)
import React from 'react';
import ReactDOM from 'react-dom';
import App from "./App"
import { BrowserRouter, Routes, Route } from "react-router-dom";
ReactDOM.render(
<BrowserRouter>
<Routes>
<Route path="*" element={() => <App />} />
</Routes>
</BrowserRouter>,
document.getElementById('root')
);
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Rubik">
<link rel="stylesheet" href="path/to/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="styles.css" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<title>React App</title>
</head>
<body>
<div id="root"></div>
</body>
<script src="../src/index.js"></script>
</html>
What am I doing wrong? Thanks!
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.
Hello I use nodeJS and I want to create an application in which I want to make a post request with a Json object from Postman or curl, my app will fetch Json Object and it will appear the object in broswer.
So, I tried to do that , but I have the problem that the json Object don't appear on broswer
(I use npm hbs, but also I tried it without that).
my nodeJS code is:
app.use(express.json())
app.use(express.urlencoded({extended:true}))
app.use('/notify',(req,res)=>{
const json = req.body
console.log(json)
res.render('index' , {
title: 'Weather App',
name:'ApLaz',
expect: JSON.stringify(json) // I tried and without JSON.stringify
})
})
With Postman request I send for example that
{
"test": "ok",
"var": 12
}
The result from console.log is :
{ ok: 'ok', var: 12 }
But on the broswer I just take this:
{}
This is my website
Why I can't appear my Json Object on broswer?
This is my index file
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="css/style.css">
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>{{title}}</title>
</head>
<body>
<!-- Header -->
{{>header}}
<!-- End Header -->
<div>
<p>Use this site for the Weather</p>
<form id="formSearch">
<input placeholder='Location' id="inputSearchValue">
<button>Search</button>
</form>
</div>
<br>
<p id="location">{{expect}}</p>
<p id="forecast"></p>
<!-- Footer -->
{{>footer}}
<!-- End Footer -->
<script src="js/app.js"></script>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<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.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
I don't have the info I need to exactly match your setup but here is a close approach. Keep in mind this is not how you would do it in a actually site but will work for learning.
You can think of dataStore as a temporary database that only exist while the app is running. In the index.html I commented out/disabled the following: header, footer, and as you didn't provided and I don't want to create them :D
I suggest you continue along the FreeCodeCamp path as it will cover data storage down the road.
package.json
{
"scripts": {
"start": "node src"
},
"dependencies": {
"express": "^4.17.1",
"mustache": "^4.1.0",
"mustache-express": "^1.3.0"
}
}
src/index.js
const mustacheExpress = require('mustache-express')
const express = require('express')
const app = express()
app.use(express.json())
app.use(express.urlencoded({extended:true}))
app.engine('html', mustacheExpress());
app.set('view engine', 'html');
app.set('views', __dirname + '/views')
let dataStore = {
expect: {user: 'jdoe', age: 30},
}
app.use('/',(req,res)=>{
res.render('index' , {
title: 'Weather App',
name:'ApLaz',
expect: JSON.stringify(dataStore.expect) // I tried and without JSON.stringify
})
})
app.use('/notify',(req,res)=>{
const json = req.body
console.log(json)
dataStore.expect = json
res.render('index' , {
title: 'Weather App',
name:'ApLaz',
expect: JSON.stringify(dataStore.expect)
})
})
app.listen(3000, (err) => {
if (err) return console.log(err)
console.log('server listening on port: %s', 3000);
})
src/view/index.html
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="css/style.css">
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>{{title}}</title>
</head>
<body>
<!-- Header -->
<!-- >header}}-->
<!-- End Header -->
<div>
<p>Use this site for the Weather</p>
<form id="formSearch">
<input placeholder='Location' id="inputSearchValue">
<button>Search</button>
</form>
</div>
<br>
<p id="location">{{expect}}</p>
<p id="forecast"></p>
<!-- Footer -->
<!-- >footer}}-->
<!-- End Footer -->
<!--<script src="js/app.js"></script>-->
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<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.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
To start the app open a terminal and run yarn start or npm start
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
Hi I am studying node js, meanwhile I am facing this issue.
app.use(express.static("public"));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
/*This route is working fine */
app.get("/:username", function (req, res) {
res.sendFile(__dirname + "/public/ui/" + "user.html");
});
/*This route is not working */
app.get("/:username/:id", function (req, res) {
res.sendFile(__dirname + "/public/ui/" + "user.html");
});
My folder Structure is
-server
-public
-ui
-ext (external files folder)
- images(all images folder)
-js (My js files folder)
-style (my css folder)
-user.html
-index.js
-user.js
When I am trying to load url http://localhost:8888/stranger/19, my page is loading but none of the files specified in user.html is not loading.
It seems like url of my css file is http://localhost:8888/stranger/ui/style/main.css instead of http://localhost:8888/ui/style/main.css.
This is happening for all files loading via ui. ("http://localhost:8888/stranger" this is coming instead of "http://localhost:8888"). How can I fix this issue
<!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">
<link rel="stylesheet" href="ui/ext/bootstrap-3.3.4/css/bootstrap.min.css" >
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="ui/style/main.css" >
<script src="ui/ext/jquery/jquery.min.js" ></script>
<script src="ui/ext/bootstrap-3.3.4/js/bootstrap.min.js" i></script>
<script src="ui/ext/moment.js" i></script>
<script src="ui/js/main.js" ></script>
<script src="ui/js/web.js" ></script>
<script src="ui/js/user_module.js" ></script>
<script src="ui/js/chat_module.js" ></script>
</head>
<body class="pz-main">
</body></html>
Add a route to static file to public directory
app.use(express.static('public'))
Here is the documentation on using the public folder
Then in your html take the path as,
<link rel="stylesheet" type="text/css" href="/ui/style/main.css">
Here are the working codes:
your app.js or server.js where the express is defined
var express = require('express');
var app = express();
app.use(express.static('public'))
app.get("/:username", function (req, res) {
res.sendFile(__dirname + "/public/ui/" + "user.html");
});
app.get("/:username/:id", function (req, res) {
res.sendFile(__dirname + "/public/ui/" + "user.html");
});
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
})
Your user.html in public/ui direcrtory.
<html>
<head>
<link rel="stylesheet" type="text/css" href="/ui/style/main.css">
</head>
<body>
Page will be in green color due to css
</body>
</html>
Your css in public/ui/style directory.
body{
background: green;
}
Follow these steps and it will work.
The problem is with href attribute.
Your current href attribute in link tag is:
<link rel="stylesheet" href="ui/ext/bootstrap-3.3.4/css/bootstrap.min.css" >
Which means to use current url as base url. Change it to following:
<link rel="stylesheet" href="/ui/ext/bootstrap-3.3.4/css/bootstrap.min.css" >
Simply add / at the start and it should fix the problem.