How can you send an html page with an image from a file via node.js - html

I am trying to send an html page with express from the node.js server but for some reason I cannot add an image that is a file
This is the code I tried:
const express = require("express");
const app = express();
app.use((req, res) => {
res.send(`<body><img src='test.png'></body>`)
});
Would appreciate help.

where should the code must look for the image?
it needs the relation address of the image in src property.
ex: '../../resources/img/test.png'

Related

How to link Node.js Post script to HTML form?

I have created a REST full APi, which works as I would be expecting if I am running Postman. I run the Test from an index.js file which would have the routes saved as per below file.
const config = require('config');
const mongoose = require('mongoose');
const users = require('./routes/users');
const auth = require('./routes/auth');
const express = require('express');
const app = express();
//mongoose.set();
if (!config.get('jwtPrivateKey'))
{
console.log('Fatal ERRORR: jwtPrivateKey key is not defined')
process.exit(1);
}
mongoose.connect(uri ,{
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
})
.then(()=>console.log('Connected to MongoDB...'))
.catch(err=> console.log('Not Connected, bad ;(', err));
app.use(express.json());
//THis is only for posting the user, e.g. Registering them
app.use('/api/users', users);
app.use('/api/auth', auth);
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}...`));
The real code is happening here. Testing this in Postmon I could establish, that the values are saved in MongoDB.
router.post('/', async (req, res) => {
//validates the request.
const { error } = validate(req.body);
if (error) return res.status(400).send(error.details[0].message);
let user = await User.findOne({email: req.body.email});
if (user) return res.status(400).send('User Already Register, try again!');
user = new User(_.pick(req.body, ['firstName','lastName','email','password','subscription']));
const salt = await bcrypt.genSaltSync(15);
user.password = await bcrypt.hash(user.password, salt);
//Here the user is being saved in the Database.
await user.save();
//const token = user.generateAuthToken();
//const token = jwt.sign({_id: user._id}, config.get('jwtPrivateKey'));
const token = user.generateAuthToken();
//We are sending the authentication in the header, and the infromation back to client
res.header('x-auth-token',token).send( _.pick(user, ['_id','firstName','lastName','email','subscription']));
});
Now my question's are:
How can I call the second code block from a , in one particular html file. When using Action="path to the users.js", the browser opens the js file code but doesn't do anything.
Do I need to rewrite the Post block part so that it would as well include the connection details to the DB? And would this mean I would keep open the connection to MongoDB once I insert Read etc.? Wouldn't this eat a lot of resources if multiple users would e.g. log in at the same time?
Or is there a way how I can use the index.js + the users.js which is refereed in the index.js file together?
All of these are theoretical questions, as I am not quite sure how to use the created API in html, then I created as walking through a tutorial.
Do I need to change the approach here?
After some longs hours I finally understood my own issue and question.
What I wanted to achieve is from an HTML page post data in MongoDB through API (this I assume is the best way how to describe this).
In order to do this I needed to:
Start server for the API function e.g. nodemon index.js, which has the information regarding the API.
Opened VS Code opened the terminal and started the API server (if I can call it like that)
Opened CMD and startet the local host for the index.html with navigating to it's folder and then writting http-server now I could access this on http://127.0.0.1:8080.
For the register.html in the form I needed to post:
This is the part which I didn't understood, but now it makes sense. Basically I start the server API seperatly and once it is started I can use e.g. Postmon and other apps which can access this link. I somehow thought html needs some more direct calls.
So After the localhost is started then the register.html will know where to post it via API.
Now I have a JOI validate issue, though on a different more simple case this worked, so I just need to fix the code there.
Thank You For reading through and Apologize if was not clear, still learning the terminology!

nodejs sendfile html page

I have this code that allows me to open a HTML page from specific folder, if I use server.js to open that HTMLpage so the page it is generating with all the css and jquery files but if I try to move the get statement to the routes folder then the page is generated but without any css and jquery files and I don't know why !
what I did in the server.js for the generation of the HTML page is below which is working perfectly :
const folderPath = __dirname + '/public/AppTemplate/src'
app.use(express.static(folderPath))
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname + '/public/AppTemplate/src/index.html'));
});
but what I'm trying now is to get the html page from routes.js :
step 1 :
I implemented this statement in server.js
app.use('/users', require('./backend/routes/profile.routes.js'));
step2 :I tried this statement in routes.js with simple modification :D :
router.get('/profile', function (req, res) {
const dirname = __dirname;
console.log(dirname)
const newpath = dirname.length - 14;
const newP = dirname.substring(newpath, dirname.lastIndexOf("/"));
console.log(newP);
res.sendFile(path.join(newP+ '/public/AppTemplate/src/02-ProfilePage.html'));
});
the step 2 is working but I couldn't get all the associated files (jquery css ...) which are located in
/public/AppTemplate/src
the image of the output is below :
hope I mentioned everything,
Best Regards,
It's because of the content in the 02-ProfilePage.html has an incorrect path.
Check the path in the script tags. If there is a slash it means that it's already in the /public/AppTemplate/src which you specified.
For example, /js/file.js will actually point to /public/AppTemplate/src/js/file.js
Perhaps try adding a / in front of your path in the script tag.
Example:
/css/x/y/z/ instead of css/x/y/z
You will have to append a / to all the routes in your script/link tag to be able to successfully load the local resources.
You can use the find and replace functionality in your code editor or IDE to speed up the process if possible.

displaying images in a .handlebars/html

I'm trying to link images to my .handlebars/html files in my views directory. I've created a public folder as I discovered was necessary, but still can't get the linked images to appear when I open my web page.
Here is my node.js code...
var express = require('express');
var session = require('express-session');
var request = require('request');
var app = express();
var handlebars = require('express-handlebars').create({defaultLayout: 'main'});
var bodyParser = require('body-parser');
app.use(session({secret:'secretSauce'}));
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.engine('handlebars', handlebars.engine);
app.set('view engine', 'handlebars');
app.set('port', 3021);
app.get('/', function (req, res, next) {
res.render('index');
});
app.get('/setup', function (req, res, next) {
res.render('setup')
});
app.use(function(req,res){
res.status(404);
res.render('404');
});
app.use(function(err, req, res, next){
console.error(err.stack);
res.type('plain/text');
res.status(500);
res.render('500');
});
app.listen(app.get('port'), function(){
console.log('Express started on http://localhost:' + app.get('port') + '; press Ctrl-C to terminate.');
});
And this is a page I've tried to load images on:
<h1>
Getting a Mailjet Account, an API, and Misc. Set Up
</h1><br>
<p>
This first part is going to their website and signing up to get an account. The sign up page looks like this. You can click on the image to take you there.
</p>
<img src="/public/images/mailjet signup.jpg" alt="sign up page">
<br>
<p>
Once you take care of business there, you can head to your account page and click on the link circled in the image below. That link will take you to where your private and public API keys are stored.
</p>
<img src="/public/images/mailjet APIKey.jpg" alt="account page">
<br>
<p>
Awesome, so the last major thing to think about is if you want to add a domain name to your account. Typically your emails that you use at sign up will be autamically set up as a sender, and it will make it look like emails are coming from that account. However, you may have multiple senders on a company domain. In that case you'll want to head over to the accuont settings and add that domain. This way in the future if employees send something it will automatically allow senders from the domain. This is really more of a logistical matter than anything, and it doesn't directly affect using this How to Guide.
</p>
<ul>
<li>Prev </li>
<li>Next</li>
</ul>
To get the images on the handlebars page or HTML we need to set the path on the index.js file or app.js file, it depends on you what is your starting page.
Index.js
app.use(express.static('views/images'));
promotionapplication\views\images - This is my folder structure, my index.js file is in promotionapplication, and i have kept my pics in the images folder. You can keep any of the structure of the folder but you should mention it in accordingly in app.use.
So now i can use any of the pics in the folder, by using the following code in handlebars page-
first.handlebars
<img src="bckground.jpg" alt="piooop" />
Remember to reload the page after the changes made.
It works perfectly fine. If any questions please comment, i will try to give an answer.
Use attachments in nodemailer options. LInk image src in your .hbs file to the unique cid in your attachment description like so:
src="cid:unique#unique"
const mailOptions = {
from: 'xxxxx',
to: x,
subject: `xxxx`,
template : 'xxx',
attachments: [
{
filename: 'xx.png',
path: __dirname +'/images/xx.png',
cid: 'unique#unique'
},]

node.js code to open a page in browser with localhost URL

I have written a simple server using node.js. At the moment the server responds by writing "hello world" to the browser.
The server.js file looks like this:
var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(8080);
I use this URL in the browser to trigger the "hello world" response:
http://localhost:8080/
I want to be able to open a basic html page when I pass a URL like this:
http://localhost:8080/test.html
I have looked through many tutorials and some stackoverflow posts but there was not much out there on this specific task. Does anyone know how to achieve this with a simple modification to the server.js file?
If you wish to open .html file through nodejs with the help of "http://localhost:8080/test.html" such url, you need to convert .html page to .jade format.Use rendering engine with the help of expressjs framework.Express rendering engine will help you to render .jade file on nodejs server.
It is better to use a front end javascript frameworks such as Angular, React or Vue to route to different pages. Though, if you want to do it in Node, you could do something like this using express:
var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.sendFile('views/index.html', { root: __dirname })
});
app.get('/test', function(req, res) {
res.sendFile('views/test.html', { root: __dirname })
});
app.listen(8080);
This is an ok solution for static pages. Express is very useful for writing REST API's.

Express routing returns undefined randomly

I am trying to learn Express with NodeJS and would like to render my views with plain HTML. I hacked together a webserver based on the Express API documentation and several Stack questions, particularly the answer by Andrew Homeyer in this question which states
You can have jade include a plain HTML page:
in views/index.jade
include plain.html in views/plain.html
... and app.js can still just render jade:
res.render(index)
My directory structure looks like this
Project
*web.js
Public
img
js
lib
gallerific
*jquery.opacityrollover.js
*jquery.gallerific.js
angular
theme
views
partials
*index.html
*index.jade
and my server looks like this.
var express = require('express'),
jade = require('jade');
var app = module.exports = express();
app.configure(function(){
app.set('views', __dirname + '/public/views');
app.use("/public/lib", express.static(__dirname + "/public/lib"));
app.use(express.static(__dirname + '/public'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.set('view engine', 'jade')
app.use(express.bodyParser());
});
app.get('/', function(req, res) {
res.render('index');
});
app.get('/partials/:name', function(req, res){
var name = req.params.name;
res.render('/public/partials/' + name);
});
app.get('/public/data/:name', function(req, res){
var name = req.params.name;
res.json('/public/data/' + name)
});
app.listen(3000, function(){
console.log("Express app listening on port %d in %s mode", this.address().port, app.settings.env);
});
What I am seeing is that certain files fail to load from directories in which everything else loads just fine. For example, my Gallery page fails to load the jquery.gallerific.js javascript file from my lib/gallerific directory while it does load the jquery.opacityrollover.js. I have poked around with Chrome Developer Tools and see the following
I had this site working with the Angular Bootstrap webserver so it doesn't seem to be a javascript error with the client side code. Does anyone know what I might doing that would cause this problem?
The source is available at https://github.com/jamesamuir/express-simple-html.git
I figured it out. It turns out I had to resolve paths that I had forgotten about so that Express could render them correctly. It wasn't that the Gallerific javascript library didn't load, it was throwing an error on the image source of undefined for my gallery images (I am pulling them from a JSON file).
Once I put the appropriate paths in for the images and the data file, everything started working again. Thanks to everyone who provided a suggestion for me. It really helped me to work through the problem.