how to send data to the client side in express js? - express

I have some bool and string variable in the server side that should be passed to client side.
how can I implement this?
in my html file I want a h1 tag if my flag in the server side is true and if flag is false it just another work. at the first my flag is false.
server.js:
app.get('/' , (req, res) => {
res.sendFile(path.join(__dirname+'/views/UiOfServer.html'));
});

I found the anwser myself, the solution is useing EJS. because server rendering is so eazy with that.
I changed my html file to EJS file and my question solved. my code is:
index.ejs:
<!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>example of EJS</title>
</head>
<body>
<% if(flag){ %>
<h1><%= username %></h1>
<% }
else{ %>
<!-- some work -->
<% } %>
</body>
</html>
server.js:
let express = require('express');
let path = require('path');
let app = express();
let router = express.Router();
app.use('/', router);
app.set('view engine', 'ejs');
const port = 2020;
app.get('/' , (req, res) => {
res.render(path.join(__dirname+'/views/UiOfServer.ejs'), {flag: false, username: 'null'});
});
app.get('/click/' , (req, res) => {
res.render(path.join(__dirname+'/views/UiOfServer.ejs'), {flag: true, username: 'Hessam :) '})
}
app.listen(port, (err, res) => {
if(err){
console.log(`Server Error: ${err}`);
}
else{
console.log(`server started on ${port}`);
}
});

Related

Trying to display ejs file but it displays the index.html instead

I'm using EJS for the first and I'm a bit confused. What's happening is that I have a list.ejs file created inside my views file. And a index.html outside I'm using a else if statement to do the logical thinking to the render my EJS file answer but when I call the res.render if I have the index.html, it displays it instead of my list.EJS, there are no errors or anything
app.js
const express = require('express');
const app = express();
const port = 3000;
app.set('view engine', 'ejs');
app.use(express.urlencoded({ extended: true }));
app.use(express.static(__dirname));
app.get('/', (req, res) => {
let today = new Date();
let currentDay = today.getDay();
let day = ""
if (currentDay === 6 | currentDay === 0) {
day = "Weekend"
} else {
day = "Weekday!"
}
res.render('list', {dayOfWeek: day})
})
app.listen(port, () => {
console.log('Listening on port ' + port);
});
list.ejs
<!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>To Do List</title>
</head>
<body>
<h1>To Do List</h1>
<h2>It's a <%=dayOfWeek%>
</h2>
</body>
</html>
The index.html is just a h1 Send Help..
What am I doing wrong?
I removed the index.html file and it works but it shouldn't be like that... Right?
Add this code:
const path=require("path");
app.set('views', path.join(__dirname));

Why will. this variable not display in Express and Nodemon

I am trying to dis displayt a simple variable in the browser using ejs.
the server.js file
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const ejs = require('ejs');
app.set('view engine', 'ejs');
mongoose.connect('mongodb+srv://<username>:<password>#cluster0.asnad.mongodb.net/?retryWrites=true&w=majority');
app.get('/',(req, res) => {
let name = 'bl;ah';
res.render('index', {
userName: name
});
})
app.listen(4000, function() {
console.log('server is running');
})
the index.ejs file is in a directory called views in the home directory mongo-html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=0.1">
<title>Document</title>
</head>
<body>
<h1>
<%= userName %> here
</h1>
</body>
</html>
The command to run the whole thing is,
nodemon server.js
Previously I installed Express and Nodemon.
I am following Marina Kim's tutorial from youtube https://www.youtube.com/watch?v=yH593K9fYvE
I don't know why this variable is not displaying.
Any help would be greatly appreciated.
Thanks,

Testcafe verification ignores specified 'timeout'

My question is pretty simple - why testcafe verifications ignore timeout, which I set in options?
For example next method, called for a page that will never be loaded, didnt wait 20 minutes until fail, it fails faster, ignoring timeout
waitForPageLoad: async (expectedUrl: string) => {
var getPageState: ClientFunction = ClientFunction(() => {
return new Promise(resolve => {
resolve(document.readyState as string);
});
}).with({ boundTestRun: testController });
await testController.expect(((await getPageState()) as string) === "complete").ok({ timeout: 1200000});
}
}
(method call and all methods above have 'await' keyword)
Is there any explanations for such thing?
You need to rewrite your assertions. See the following example based on the changeable document.a property:
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
document.a = '0';
window.setTimeout(() => { document.a = '1' }, 10000)
</script>
</body>
</html>
test.js
import { ClientFunction } from 'testcafe';
fixture `Fixture`
.page('./index.html');
test('test', async t => {
const getPageState = ClientFunction(() => {
return new Promise(resolve => {
resolve(document.a);
});
});
await t.expect(getPageState()).eql('1', { timeout: 1000 }); // it fails, increase the timeout (15000) to pass
});

How to change initially generated title after file build in index.html

I have downloaded a vue.js template from the web. Whenever I build files via npm the title on the index.html keeps being swapped to the name of the template. Is there a way to change the default title?
As I understand your question - you need to configure your vue.config.js file something like this (pay attention on Webpack part) - these files are from working project, so you have maximum understanding on how it could look at the end:
module.exports = {
baseUrl: '/',
outputDir: (process.env.NODE_ENV === 'production' ? '../web/' : '../web/js/'),
indexPath: '../app/Resources/views/index.html.twig',
// Setting this to false can speed up production builds if you don't need source maps for production.
productionSourceMap: false,
// By default, generated static assets contains hashes in their filenames for better caching control.
// However, this requires the index HTML to be auto-generated by Vue CLI. If you cannot make use of the index HTML
// generated by Vue CLI, you can disable filename hashing by setting this option to false,
filenameHashing: false,
lintOnSave: false,
// https://cli.vuejs.org/ru/config/#devserver-proxy
devServer: {},
// https://cli.vuejs.org/ru/config/#chainwebpack
chainWebpack: config => {
config
.plugin('html')
.tap(args => {
args[0].title = 'Ojok Deep Sales Platform';
args[0].template = './index.html.template';
return args;
})
}
};
And after you have updated your vue.config.js file, change your index.html template file to be like this:
<!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, shrink-to-fit=no">
<title><%= htmlWebpackPlugin.options.title %></title>
<link href='https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900' rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Material+Icons" rel="stylesheet">
<script type="text/javascript" src="../js/go.js"></script>
<script type="text/javascript" src="../js/momentjs.js"></script>
<script type="text/javascript" src="../js/webphone/flashphoner.js"></script>
<script type="text/javascript" src="../js/webphone/SoundControl.js"></script>
</head>
<body>
<div id="app"></div>
</body>
</html>
Pay attention on what is being included in <title>-tag:
<title><%= htmlWebpackPlugin.options.title %></title>
After generating new index.html file your title should be set to whatever you have written into args[0].title option.
Hope this helps.
I'm still new at VueJS, but here were my findings. I'd love any suggested options or improvements. I went with option #2.
Option 1: set for Multiple Pages mode
vue.config.js
module.exports = {
pages: {
index: {
entry: 'src/main.js',
// template title tag needs to be <title><%= htmlWebpackPlugin.options.title %></title>
title: 'My Website Title',
},
}
}
Option 2: titleMixin (referenced from https://medium.com/#Taha_Shashtari/the-easy-way-to-change-page-title-in-vue-6caf05006863)
titleMixin.js added to mixins folder
function getTitle (vm) {
const { title } = vm.$options
if (title) {
return typeof title === 'function'
? title.call(vm)
: title
}
}
export default {
created () {
const title = getTitle(this)
if (title) {
document.title = title
}
}
}
added to main.js
import titleMixin from './mixins/titleMixin'
Vue.mixin(titleMixin)
Use in Component Pages
<script>
export default {
title: 'Foo Page'
}
</script>
Use in Vue instance with a function
<script>
export default {
title () {
return `Foo Page — ${this.someValue}`
},
data () {
return {
someValue: 'bar'
}
}
}
</script>
Option 1:
Edit your /public/index.html and replace this:
<title><%= htmlWebpackPlugin.options.title %></title>
with this:
<title>Your Title Here</title>
Option 2:
vue.config.js
module.exports = {
chainWebpack: config => {
config.plugin('html').tap(args => {
args[0].title = 'Your Title Here';
return args;
});
}
}
/public/index.html
<title><%= htmlWebpackPlugin.options.title %></title>

Connection closed before receiving a handshake response with deepstream + express

I wanted to test deepstream with express.
Found this template https://github.com/deepstreamIO/ds-tutorial-express
But when I run it I get the error message:
Connection closed before receiving a handshake response
Why isn't this example working?
Server.js
var Deepstream = require( 'deepstream.io' );
var http = require( 'http' );
var express = require( 'express' );
var deepstream = new Deepstream();
var app = express();
var server = http.createServer(app);
app.get('/hello', function ( req, res ) {
res.send( 'Hello to you too!' );
})
deepstream.set( 'httpServer', server );
deepstream.start();
server.listen( 6020, function(){
console.log( 'HTTP server listening on 6020' );
});
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example Client</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- libraries -->
<script type="text/javascript" src="https://rawgit.com/deepstreamIO/deepstream.io-client-js/master/dist/deepstream.min.js"></script>
</head>
<body>
<script>
var ds = deepstream( 'localhost:6020' );
ds.login( {}, function( success, errorEvent, errorMessage ) {
console.log( 'Logged in to deepstream' );
});
</script>
</body>
</html>
BR
On the client, could you switch to this CDN link
<script src="https://cdnjs.cloudflare.com/ajax/libs/deepstream.io-client-js/1.1.1/deepstream.js"></script>
the rawgit one is pointing to the master branch which is already at 2.0 and incompatible with the 1.x server