How would I go into retrieving data from expressJS? That is without it getting overwritten, or redirecting a user.
<html>
<body>
<h1>Retrieved data</h1>
</body>
</html>
for example how would i go into adding it if the server side looks like this?
var express = require("express");
var app = express();
app.get("/", function (req, res) {
res.sendFile(__dirname + "/index.html");
//how do i add data to the <h1> tag
});
app.listen(10022, function () {
console.log("server is up");
});
You wouldn't be able to do it with a .html file. You'd need an EJS file. The markup for that would look like this.
<html>
<body>
<h1>Retrieved <%= data %></h1>
</body>
</html>
Then you'll need the ejs module. Run the following NPM command.
npm install ejs
So change your index.html to index.ejs, make sure it's in a directory named views, and then modify your server side code to this.
var express = require("express");
var app = express();
app.set("view engine", "ejs");
app.get("/", function (req, res) {
res.render("index", {data: 'This is the data'});
});
app.listen(10022, function () {
console.log("server is up");
});
EJS is a templating language that converts to HTML, taking the data object you've passed in through your render method, rendering it server side, and then sending it to the browser.
Related
local host is not loading when partials(ejs templates) are added to the pages.The page loads at first if the partials are not added.But once the partials are added the page no longer loads.Also no error is also being reported.The page keeps on loading and finally shows unable to reach the adress.
var express = require("express");
var app = express();
var bodyparser = require("body-parser");
app.use(bodyparser.urlencoded({extended: true}));
app.set("view engine", "ejs");
app.get("/", function(req , res){
res.render("landing");
});
app.get("/campgrounds", function(req,res){
res.render("campgrounds",{campgrounds:campgrounds});
});
app.post("/campgrounds",function(req,res){
var name = req.body.name;
var image = req.body.image;
var newCamp = {name: name, image:image}
campgrounds.push(newCamp)
res.redirect("/campgrounds");
});
app.get("/campgrounds/new", function(req, res){
res.render("new.ejs");
});
app.listen(3000, function(){
console.log("Yelp camp server has started");
});
when the headers are added to the the following page the page no longer loads
<%- include('partials/header.ejs') %>
<h1>landing page</h1>
view all campgrounds
<p>asdasdasda</p>
<%- include('partials/footer.ejs') %>
Please help!!!!
also here is the code for the header
<!DOCTYPE html>
<html>
<head>
<title>YELPCAMP</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >
</head>
<body>
<p>header tabs</p>
You're missing a - from the closing tag:
<%- include('partials/header.ejs') -%>
...
<%- include('partials/footer.ejs') -%>
Thanks for the help ,
The problem was occurring because of an incorrect bootstrap cdn and the partials declaration.
Fixed those issues and the app is now working fine.
I'm trying to use the login templates (Took from: 50 Free HTML5 And CSS3 Login Forms For Your Website 201
My directory set up is like this :
-css
|
-- style.css
- js
|
-- index.js
|
index.html
The head of the index.html file looks:
<head>
<meta charset="UTF-8">
<title>Sign-Up/Login Form</title>
<link href='http://fonts.googleapis.com/css?family=Titillium+Web:400,300,600' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel="stylesheet" href="css/style.css">
</head>
and the body contains the includes scrips:
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src="js/index.js"></script>
My node.js looks:
// Import Required Module
var express = require('express')
var app = express()
var bodyParser = require('body-parser')
// css
var path = require('path')
app.use(express.static(path.join(__dirname, 'public')));
// Create instances
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
// Get
app.get('/', function (req, res) {
console.log('Get: /');
res.sendFile('LoginTemplate/index.html', {root: __dirname })
})
/*
app.get('css/style.css', function (req, res) {
console.log('Get: css/style.css');
res.sendFile('css/style.css', {root: __dirname })
})
*/
// Listner
app.listen(3001, function () {
console.log('Example app listening on port 3001!')
})
When loading the html file I'm getting the error:
GET http://127.0.0.1:3001/css/style.css
I have tried to look for solution at:
Can not get CSS file
And created the public folder and copy the css folder inside, but it still doesnt work.
How can I load the css & js files ?
// Import Required Module
var express = require('express')
var app = express()
var bodyParser = require('body-parser')
// Create instances
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
// Get
app.get('/', function (req, res) {
console.log('Get: /');
res.sendFile('LoginTemplate/index.html', {root: __dirname })
})
app.get('/css/style.css', function (req, res) {
console.log('Get: css/style.css');
res.sendFile('LoginTemplate/css/style.css', {root: __dirname })
})
app.get('/js/index.js', function (req, res) {
console.log('Get: js/index.js');
res.sendFile('LoginTemplate/js/index.js', {root: __dirname })
})
// Listner
app.listen(3001, function () {
console.log('Example app listening on port 3001!')
})
Everything looks good in your code and folder setup. From the URL you are posting (http://127.0.0.1:3001/css/style.css), I am guessing that the error lies in your server instance. Check the definition files and make sure that the server has permission to read css/style.css.
I have run into this problem when the file and folder do not have the right permissions. A quick check for this is running something similar to sudo chmod -R 0777 [path_to_your_project] (linux and Mac systems will use this command). This command gives full access to all users and guests to read, write and execute your files and is a quick way to verify whether the problem is user rights.
I have also run into this same problem when my web server is not correctly configured. In those cases, I had accidentally allowed the web server to share all files in the root folder (eg: /var/www ), but not any sub folders, so (using the example) the folder /var/www/images would be parsed by the web server and seen as an area that is protected. In this case, the Web Server has access, but it refuses to serve the files based on the configuration rules.
I hope one of these two fixes helps direct you down the right path to a solution.
Good luck!
I am very novice at Node.
I made the server run as follows (index.js):
var express = require('express'),
views = require('./routes/views');
var app = express();
// Get an instance of router
//var router = express.Router();
//app.use(express.static(__dirname+'/routes/keenIO/assets/css'));
app.use('/', views);
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
I use the router in this way, setting also the, I guess correct ones, paths to the static content (views.js):
var express = require('express');
var path = require("path");
var router = express.Router();
router.use('/assets', express.static(__dirname+'/keenIO/assets'));
router.use('/specificAssets', express.static(__dirname+'/keenIO/examples'));
//app.use(express.static(__dirname+'/routes/keenIO/assets/css'));
router.get('/', function(req, res) {
//res.send('GET handler for /views route.');
var indexPatch = path.join(__dirname+'/keenIO/examples/connected-devices/index.html');
res.sendFile(indexPatch);
//res.send(__dirname);
});
router.get('/rules', function(req, res) {
//res.send('GET handler for /views route.');
var indexPatch = path.join(__dirname+'/keenIO/examples/connected-devices/rules.html');
res.sendFile(indexPatch);
//res.send(__dirname);
});
router.get('/json', function(req, res) {
//res.send('POST handler for /views route.');
var fs = require('fs');
//res.send('HOLA MUNDO');
var obj;
fs.readFile('network-big.json', 'utf8', function (err, data) {
if (err) throw err;
obj = JSON.parse(data);
res.send(obj);
});
});
module.exports = router;
So, In the .html file I use for example this to reach to the css, and similar to reach to the javascript files:
<link rel="stylesheet" type="text/css" href="assets/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="assets/css/keen-dashboards.css" />
<link rel="stylesheet" type="text/css" href="specificAssets/connected-devices/connected-devices.css" />
I start this and everything is fine, but as I try to load the same index.html for example clicking on a link ( with the path to it: specificAssets/connected-devices/index.html) it has no style at all.
EDITED 25/10/16 3:30 p.m:
Well, inspecting the element with Chrome, as I click on the links I get doubled one part of the patch, getting for some static resources http://localhost:3000/assets/assets/resource.{css/js}
But it appropriately loaded the first time I access to the .html with http://localhost:3000. I am confused...
Any advise will be very appreciated.
Best regards,
Iván
Create a proper structure and keep all your html files in a views folder and do it following way that will work for you And for styling just keep your css in html file only or keep them in same folder and require file in html Easiest way to do is to keep your html and style in same file
router.set('views', path.join(__dirname, 'views'));
router.get('/', function(req, res) {
res.render('index');
});
If you want to use a proper structure then you need to know this thing as well
Since .css files are static files you have to serve them to the clients. However, you do not serve static files as a express middleware. Add the following middleware to your express app and move the css folder under the public directory (you should create a public directory)
app.use(express.static(path.join(__dirname, 'public')));
I'm building a Express app using React. I start my server, go to localhost and I see a blank page, when I check the developer tools on chrome it shows me that my js file is plain HTML. Why is that?
This is my server.js:
var express = require('express');
var app = express();
var port = process.env.NODE_ENV || 3000;
app.get('*', function(req, res) {
res.sendFile(__dirname + '/public/views/index.html');
});
app.listen(port, function() {
console.log('Listening to http://localhost:' + port);
});
This is my app.js:
var React = require('react'),
ReactDOM = require('react-dom');
var App = React.createClass({displayName: "App",
render () {
return (
React.createElement("h1", null, "Hello World!!!!!")
)
}
});
ReactDOM.render(React.createElement(App, null), document.getElementById('main-app'));
My index.html:
<body>
<div id="main-app"></div>
</body>
<script src="public/assets/dist/javascripts/app.js"></script>
This is what I see on developer tools:
image
The problem is that whatever file you are requesting to your server you are always returning index.html.
So when you go to http://localhost:3000/ you get index.html
The problem is that your index.html then requests public/assets/dist/javascripts/app.js but you still return index.html as if it was app.js.
You need to update your route so it returns the file that was requested.
I think adding this to your server.js might fix it.
app.use(express.static(__dirname + '/public'));
Instead of
app.get('*', function(req, res) {
res.sendFile(__dirname + '/public/views/index.html');
});
I use this function to send html file to client, but in client I get nothing (blank page) without error. Something I wrong?, please help?
var express = require('express');
var fs = require('fs');
var app = express();
app.set('view engine', 'jade');
app.engine('jade', require('jade').__express);
app.get('/test', function(req, res) {
fs.readFile(__dirname + '/views/test.html', 'utf8', function(err, text){
res.send(text);
});
var port = process.env.PORT || 80;
var server = app.listen(port);
console.log('Express app started on port ' + port);
My test.html file
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style something here </style>
<title>Test</title>
<script src="..."></script>
</head>
<body>
<div> Somthing here </div>
<script type="text/javascript">
//something here
</script>
</body></html>
Try your code like this:
var app = express();
app.get('/test', function(req, res) {
res.sendFile('views/test.html', {root: __dirname })
});
Use res.sendFile instead of reading the file manually so express can handle setting the content-type properly for you.
You don't need the app.engine line, as that is handled internally by express.
you can render the page in express more easily
var app = require('express')();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.get('/signup',function(req,res){
res.sendFile(path.join(__dirname,'/signup.html'));
});
so if u request like http://127.0.0.1:8080/signup that it will render signup.html page under views folder.
After years, I want to add another approach by using a view engine in Express.js
var fs = require('fs');
app.get('/test', function(req, res, next) {
var html = fs.readFileSync('./html/test.html', 'utf8')
res.render('test', { html: html })
// or res.send(html)
})
Then, do that in your views/test if you choose res.render method at the above code (I'm writing in EJS format):
<%- locals.html %>
That's all.
In this way, you don't need to break your View Engine arrangements.
The "../" is considered malicious and will result in ForbiddenError: Forbidden at SendStream.error... exception.
The way to go is using a path module:
var path = require('path');
res.sendFile(path.resolve('views/auth/success.html'));
var app = express();
app.get('/test', function(req, res) {
res.sendFile(__dirname + "/view/test.html")
});
Here __dirname, gives you the current path where your files are saved. So in res.sendFile(), we first tell our current location by __dirname + (then we locate the specific file which should we shown on the home page i. e ) "vies/test.html".
Follow this simple process and send html file ->
res.sendfile("views/home.html"); // don't use capitla latter F with sendFile you must be use small letter f
example : sendfile();