routing a webpage error, nodejs and expressjs - node.js

I am trying to route directly to the html file using express.js, getting an unknown error, being new to express.js, I couldn't get how to resolve this one:-
here is the js code :-
const express = require('express');
const path = require();
const app = express();
const port=process.env.PORT || 8000;
// public static path
const static_path = path.join(__dirname,"../public");
app.use(express.static(static_path));
app.get("",(req,res)=>{
res.send("welcome to this main page");
})
app.get("/about",(req,res)=>{
res.send("welcome to this about page");
})
app.get("/weather",(req,res)=>{
res.send("welcome to this weather page");
})
app.get("*",(req,res)=>{
res.send("404 Error page oops");
})
app.listen(port,()=>{
console.log(`listening to the port ${port}`);
})
static web page:-
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>Weather App</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<h1>Welcome to the static web</h1>
</body>
</html>
getting this error:-
internal/validators.js:124
throw new ERR_INVALID_ARG_TYPE(name, 'string', value);
^
TypeError [ERR_INVALID_ARG_TYPE]: The "id" argument must be of type string. Received undefined

ok, I was using "type nul > filename" command for creating new files in attached folders. When I used directly the VSCode feature of creating files, it's working fine now,... don't know why, but I think that old command might have expired, tell me if I am wrong, but I just solved my issue...

Related

How to change the line "var domToPdf = require('dom-to-pdf');"

I want to use a NodeJs Module on the browser. I read, that I can do this with http://browserify.org/.
Concret I want to use this NodeJs Module: https://github.com/ovvn/dom-to-pdf
So I create a bundle.js form this like explained here: http://browserify.org/
You can see my bundle in my github repo: https://github.com/astridx/dom-to-pdf/blob/javascriptexport_browserify/bundle.js
But now I do not know how to go on. I created an example: https://github.com/astridx/dom-to-pdf/blob/javascriptexport_browserify/example/index.html
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="./../bundle.js"></script>
</head>
<body>
<div id="test">TODO write content</div>
<script>
var domToPdf = require('dom-to-pdf');
var element = document.getElementById('test');
var options = {
filename: 'test.pdf'
};
domToPdf(element, options, function () {
console.log('done');
});
</script>
</body>
</html>
But I do not know how to change the line var domToPdf = require('dom-to-pdf');
Can someone give me a hint?
Try using import instead, but you might need babel for that to work properly.
e.g import domToPdf from 'dom-to-pdf';

How to re-translate image from other website (hiding source URL)

I have a link to the image like
this or that.
I'm trying to re-translate this image from other source URL to some link, f.e http(s)://examplewebsite.com/john.
So, it doesn't need to be a redirect, but rather "showing" image on a different link. I've tried using express.static but it doesn't work.
Thanks in advance
If I understand it right, you have your express server and you want to include foreign images in response while hiding source url
In the simplest form, every time someone requests your page, you would fetch the image you want, encode it in base64 and include this base64 as src for the img
const express = require('express')
const fetch = require('node-fetch')
const app = express()
const port = 3000
app.get('/', (req, res) => {
fetch('https://www.gravatar.com/avatar/fdb4d2674d818861be4a4139469ebe59?s=48&d=identicon&r=PG&f=1')
.then(res => res.buffer())
.then(buffer => {
res.send(`
<!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>
<p>hello</p>
<img src="data:image\png;base64, ${buffer.toString('base64')}" alt="image">
</body>
</html>
`)
})
})
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
ideally you would create a separate endpoint for these images and also cache them (in memory or on hard drive) to not re-download them every time you need them

How to expose a static html page from ionic

I have a static html page which intercept authorization message, I'd like to expose this on the domain. It looks like so:
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>JwtAuthDemo - Facebook Auth</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="assets/util.js"></script>
</head>
<body>
<script>
// if we don't receive an access token then login failed and/or the user has not connected properly
var accessToken = getParameterByName("access_token");
var message = {};
if (accessToken) {
message.status = true;
message.accessToken = accessToken;
}
else
{
message.status = false;
message.error = getParameterByName("error");
message.errorDescription = getParameterByName("error_description");
}
window.opener.postMessage(JSON.stringify(message), "http://localhost:5000");
</script>
</body>
</html>
If I place this page next to the index.html page it is not exposed, however when I place it inside the assets folder it can be access. I'm guessing I have to explicitly expose the page in one of the json config files however I'm not to sure how to do so?
I'd prefer not to have my redirect url be www.mydomain.com/assets/oauth-response-parser.html. I'd like to keep this in my application seeing as it's part of the application.
How can I expose a static html page from Ionic as a sibling to the index.html page ?
You can automatically get files to your assets directory by specifying that you want to run a custom script during your ionic builds.
In your package.json you'd have a 'config' section where you can specify this script:
...
"config": {
"ionic_copy": "./config/customCopy.config.js"
},
...
and then your customCopy.config.js would contain an entry to copy over your html into assets:
module.exports = {
copyAssets: {
src: ['{{SRC}}/assets/**/*'],
dest: '{{WWW}}/assets'
}
}
More info on this process at the ionic app scripts page
I hope this steers you in the right direction.

Uncaught SyntaxError: Unexpected token < for JavaScript files

I am developing a MEAN stack CRUD project . After build my project I am getting this error from index.html file in dist/ngAppVideos/index.html folder.i tried <base href="/"> but no luck.
This is my index.html file
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>NgAppVideos</title>
<base href="/ngAppVideos/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
<script type="text/javascript" src="runtime.js"></script>
<script type="text/javascript" src="polyfills.js"></script>
<script type="text/javascript" src="styles.js"></script>
<script type="text/javascript" src="vendor.js"></script>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
This is server.js file
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const api = require('./server/routes/api');
const port = 3000;
const app = express();
api.use(express.static(path.join(__dirname, 'dist')));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/api', api);
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/ngAppVideos/index.html'));
});
app.listen(port, function () {
console.log("Server running on localhost:" + port);
});
I tried many ways like modifying base-href location in index.html file but didn't work
in my server.js I changed my __dirname to dist/index.html but this time it just prompt No such directory can be found..error.
Thanks!
you have a few mistakes:
1)for set public file to dist must be set the full path of dist.maybe is there in a subdirectory or anything like this.
2)in your node.js code, you tell return all GET request by an HTML file and in front-end code, you get a javascript file but your server code sends an HTML file and front-end wait for javascript code but get HTML file and send you this error.
to solving these problems must be set a correct public folder and put your javascript file to it and change get javascript path in front, for example
set public like this:
app.use(express.static(path.join(__dirname, 'subdirectory/dist')))
and change script tag to:
<script type="text/javascript" src="/runtime.js"></script>
don't forget put your javascript file in dist folder

html-webpack-plugin - How to insert webpack bundle.js without executing the EJS template

I am trying to insert bundle.js dynamically without executing the EJS template but I get the below error. Is there a way to insert just the JS without executing the EJS template?
ERROR in Template execution failed: ReferenceError: description is not defined
ERROR in ReferenceError: description is not defined
I am actually rendering the template using node and I just want the bundle file to be dynamically inserted in the template.ejs
res.status(200).render('template',
{
description: description,
title:title
});
webpack config:
output: {
path: path.join(__dirname, 'dist'),
filename: "output.[hash].bundle.js",
publicPath: '/'
},
new HtmlWebpackPlugin({
inject: 'body',
template: 'views/template.ejs'
}),
template.ejs
<!DOCTYPE html>
<html lang="en" class="ddhub-site">
<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">
<meta name="format-detection" content="telephone=no">
<meta description=<%=description%>/>
<title> <%= title %> </title>
</head>
<body></body>
</html>
I ended up using a simple custom plugin with the information posted on one of the github issue.
var fs = require("fs");
const path = require('path')
function UpdateBundleJsPlugin(options) {
// Setup the plugin instance with options...
}
UpdateBundleJsPlugin.prototype.apply = function(compiler) {
compiler.plugin("done", function(statsData) {
const stats = statsData.toJson();
if (!stats.errors.length) {
const htmlFileName = "search.ejs";
const html = fs.readFileSync(path.join('./views',htmlFileName), "utf8");
// need to read the final js bundle file to replace in the distributed index.html file
const asset = stats.assets[0];
let htmlOutput = html.replace(/static\/.*bundle\.js/, 'static/'+asset.name);
fs.writeFileSync(
path.join('./views', htmlFileName),
htmlOutput);
}
});
};
module.exports = UpdateBundleJsPlugin;
Why not use:
plugins: [
new HtmlWebpackPlugin({
hash: true,
template: 'ejs-render!./dev/index.ejs',
inject: 'body'
})
]
With the ejs-render-loader:
https://github.com/tracker1/ejs-render-loader

Resources