Sending data object to another page using nodeJS and EJS - javascript

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>

Related

CSS file is not connecting in an express app

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}`)
})

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 })

res.send Not sending any data - Express.js

So I am working on this calculator app using Express.js and when I use the res.send Method I am not receiving any kind of response now.
I expect my webpage to send me the sum as in the calculator.js file.
I am using nodemon as well.
This is HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calculator</title>
</head>
<body>
<h1>Calculator</h1>
<form method="POST">
<input name='num1' placeholder='num1' type='text'>
<input name='num2' placeholder='num2' type='text'>
<button
type="submit" name="submit">Calculate</button></form>
<h1 class='answer'></h1>
</body>
</html>
This is calculator.js
const express = require('express');
const app = express();
const port = 3000;
const bodyParser = require("body-parser");
const {
json,
urlencoded
} = require('body-parser');
app.use(bodyParser.urlencoded({
extended: true
}));
app.get("/", function (req, res) {
res.sendFile(__dirname + "/index.html")
});;
app.post("/", function (req, res) {
console.log(req.body);
var num1 = Number(req.body.num1);
var num2 = Number(req.body.num2);
var sum = num1 + num2;
res.send(sum);
});
app.listen(port, () => console.log(`Example app listening on port port!`))
you can't use res.send() to send number, it will be sent as a http status code. You can simply convert calculated sum to string and then send it:
res.send(sum.toString())
res.send has been deprecated in the latest version of Express (4.17.1).
Using res.sendStatus instead solved my problem.

How to get into html source code by rest request

I want to render some value of another website by fetching the HTML source data by REST request, console the value inside the span tag to my console log and render it to my HTML.
I can't managed to this by my current code, he receives the data before the DOM is ready and the specific san tag i need still not there.
My current code -
async function uiTagChecking() {
let url ='http://production.com:8000/loginPage#';
fetch(url)
.then(await sleep(6000))
.then(response => response.text())
.then(pageSource => console.log(pageSource));
}
The current source code I've fetched (this is before the DOM is ready and the needed span tag doesn't there yet)
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>loading...</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link rel="icon"
type="image/png"
href="images/favicon.png?v=9">
<!--<link href="assets/vendors/keylines/map/leaflet.css" rel="stylesheet">-->
<link href="XXXX" rel="stylesheet"></head>
<body>
<div id="app"></div>
<script src="assets/vendors/jquery.min.js"></script>
<script type="text/javascript" src="XXXX/index-c08574aac712ae81e016.js"></script></body>
</html>
The span tag i want to print and render -
<span class="version-for-qa">2.1.1</span>
But it appears only after the redirect is ended and the DOM is ready.
Technical info:
Node JS
JavaScript
HTML + CSS
My server file (express):
var express = require('express');
var cors = require('cors');
var app = express();
var path = require("path");
var fetch = require('fetch-cookie')(require('node-fetch'));
var btoa = require('btoa');
var http = require('http');
var fs = require('fs');
var corsOptionsDelegate = function (req, callback) {
var corsOptions;
if (whitelist.indexOf(req.header('Origin')) !== -1) {
corsOptions = { origin: true } // reflect (enable) the requested origin in the CORS response
}else{
corsOptions = { origin: false } // disable CORS for this request
}
callback(null, data , corsOptions) // callback expects two parameters: error and options
};
app.engine('.html', require('ejs').__express);
app.set('views', __dirname + '/view');
app.set('view engine', 'html');
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res){
res.render('index');
res.render('logo');
res.writeHead(200, {'Content-Type': 'application/json'});
});
app.use(cors());
app.set(['$qProvider', function ($qProvider) {
$qProvider.errorOnUnhandledRejections(false);
}]);
app.get('/products/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
});
app.listen(8033, function () {
console.log('CORS-enabled web server listening on port 8033')
});

"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