how to display image in angular saved on node server - node.js

I have a nodejs app running on localhost:3000, I uploaded images using multer, so they are in ./uploads/ folder. In the Angular app running on locahost:4200 I want to retrieve those images.
in my for loop:
<tr *ngFor="let data of empData;let i=index">
<td>{{i+1}}</td>
<td>{{data.emp_name}}</td>
<td><img src="./uploads/{{data.emp_image}}"></td>
</tr>
I have all data in following result variable:
this.emp.viewData().subscribe(
res => {
this.empData = res;
},
err => {
console.log(err);
},
)

In addition to the answer above by Software Person, ensure you include this to you node application to enable you access the uploads directory in your nodejs application.
const express = require('express');
const app = express();
app.use(express.static('uploads'));
Happy Coding.

You could include your full url like
<tr *ngFor="let data of empData;let i=index">
<td>{{i+1}}</td>
<td>{{data.emp_name}}</td>
<td><img src="http(s)://localhost:3000/uploads/{{data.emp_image}}"></td>
</tr>
Or even better you could define a variable in component and use it like this:
<tr *ngFor="let data of empData;let i=index">
<td>{{i+1}}</td>
<td>{{data.emp_name}}</td>
<td><img src="{{SERVER_UPLOAD_DIR}}/{{data.emp_image}}"></td>
</tr>

Related

Unable to display the uploaded image in express node project? Please support

want to display the image which was uploaded in server,but unfortunately not getting.
Image is uploaded successfully in server and changed the name in express project folder,but while fetching not getting the image.
Additional route path is coming in front of image while fetching.Image is stored in server in this path "public/images/1670147053485apic.jpg"
please find my route file users.js below:
router.get('/display', (req, res) => {
sql = `SELECT * FROM product`
db.query(sql, (err, result) => {
if (err) throw err
res.render('insertDisplay', { data: result })
})
})
also insertDisplay.hbs details below:
<table>
<thead>
<tr>
<th>Product</th>
<th>Category</th>
<th>Time</th>
<th>Image</th>
</tr>
</thead>
<tbody>
{{#each data}}
<tr>
<td>{{this.Product}}</td>
<td>{{this.Category}}</td>
<td>{{this.date}}</td>
<td><img src="{{this.Image}}"></td>
</tr>
{{/each}}
</tbody>
</table>
In running log am getting
GET /users/1670147053485apic.jpg 404 103.009 ms - 1407
but not displaying any image
screenshot currently getting the output:
Issue Resolved:- (Express-Generator,Handlebars,MySql these are my working environment)
An image file is uploaded into express application(or server) and its name is stored in database.(No Issue-uploaded successfully)
But not able to display the image using handlebars,while try to display from db(this was the real issue faced).
Changes made in 'insertDisplay.hbs' file, now its working(
changes made)
My express app structure, images stored in 'public/images' location.
Screenshot for further reference:-user.js(route for insert and display image-user.js),databse.js(db connection configuration-databse.js).
Thanks for support -Konrad,Tiddo

CustomMessage Lambda throwing error due to emailBody ( {####} )

Context:
I am having one NodeJS app holding my Lambda trigger handlers of my Cognito UserPool. That app has multiple NodeJS client apps. I am having multiple ForgetPassword html templates (for emails) for each of my client apps.
Problem:
I am encountering a problem with CustomMessage Lambda for ForgetPassword trigger with one the client apps, where I am having the following error (copy/pasted from my Postman):
at 'emailBody' failed to satisfy constraint: Member must satisfy regular expression pattern: [\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}\\s*]*\\{####\\}[\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}\\s*]*
It is mentioned in AWS documentation (in here) that emailMessage must contain: {####}. For my email templates I did include that. But what's strange is that client app 1 works fine (the correct template get sent and the {####} get replaced by the code generated by Cognito), but client app 2 doesn't (It throws the error displayed above).
I also want you to highlight that: in the error, it is said that the template didn't respect the regex which should verify that the template has {####}, but the regex of the error does check for \{####\}. Why is that? the regex should be {. . .}*\{####\}{. . .} instead of {. . .}*\\{####\\}{. . .}.
Code:
CustomMessage ForgotPassword trigger handler:
module.exports.customMessageHandler = async (event, context, callback) => {
// LOGIC IN HERE . . .
if (event.triggerSource === "CustomMessage_ForgotPassword") {
if (//check which app is it: app 1 or app 2 to choose the correct template) {
let message = async readFile(path_to_right_template);
event.response.emailMessage = message;
event.response.emailSubject = 'Forgot password recovery';
console.log(message). // I log the html template to make sure that it holds the {####}, and it does!
}
}
callback(null, event);
}
Email HTML Template
<div> . . . content </div>
<table border="0" cellpadding="0" cellspacing="0" class="html_block"
role="presentation"
style="mso-table-lspace: 0pt; mso-table-rspace: 0pt;"
width="100%">
<tr>
<td>
<div align="center"
style="font-family:Ubuntu, Tahoma, Verdana, Segoe, sans-serif;text-align:center;">
<div class="our-class"
style="margin:0 auto; height:40px; width:120px; background-color:#c2daf2; padding-top:10px;border-radius: 10px;">
{####}
</div>
</div>
</td>
</tr>
</table>
<div>content . . .</div>
Thank you all for your assistance, please let me know if I am missing any information that could help debug this issue.

Can't get footable to display

I'm new to ASP and MVC so I'm learning. I'm trying to implement footable in my ASP.NET MVC 5 test project (I ultimately want to use the pagination and sorting features, but one step at a time).
I have added the .js files and .css files to the project and included them in the BundleConfig.cs file (see below). I'm not sure if that is all I need to do in order to use them in my project.
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js",
"~/Scripts/footable.min.js",
"~/Scripts/footable.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css",
"~/Content/footable.bootstrap.min.css",
"~/Content/footable.bootstrap.css"));
I'm retrieving data from a MySQL database and passing that to my view but I'm just getting a standard html table, what am I doing wrong ?
Here is the view code :-
#model IEnumerable<MVC5Footable.Models.radacct>
#{
ViewBag.Title = "Index";
}
<table class="footable">
<thead>
<tr>
<th>#Html.DisplayNameFor(model => model.username)</th>
<th>#Html.DisplayNameFor(model => model.framedipaddress)</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>#Html.DisplayFor(modelItem => item.username)</td>
<td>#Html.DisplayFor(modelItem => item.framedipaddress)</td>
</tr>
}
</tbody>
</table>
<!-- Initialize FooTable -->
<script>
jQuery(function ($) {
$('footable').footable();
});
</script>
Hoping someone can help. Thanks.
A little late, but for the record: you forgot to include the dot.
$('.footable').footable();

Node.js and Express handlebars - 404 Error

For my class I have to design an app that says at the top of the page whether an incoming request is GET or POST, then has to print a table that shows all parameter names and values that were sent in the URL query string, and the property names and values that were received in the request body.
So far I have been able to get my localhost:port to work, it correctly shows whether a request is GET or POST. But when I go to the subpage that is supposed to display the tables, I get a 404 instead.
Here is the render page that I think is causing the problem:
function runQ(req) {
console.log(req.qParams);
console.log(req.body);
var context = {};
context.queryParams = [];
context.bodyParams = [];
context.queryCount = 0;
context.bodyCount = 0;
for( var p in req.qParams) {
context.queryCount++;
context.queryParams.push({'name': p, 'value': req.qParams[p] });
}
for( var p in req.body) {
context.bodyCount++;
context.bodyParams.push({'name': p, 'value': req.body[p] });
}
context.methodType = req.method;
return context;
}
app.get('/request', function(req, res) {
res.render('request', runQ(req));
});
app.post('/request', function(req, res) {
res.render('request', runQ(req));
});
I have a request.handlebar saved in my ubuntu/getpost/views folder along with the 404 and 500 handlebars.
The command I use for testing is:
$ curl --data "a=1&b=2&c=3" localhost:port
I replaced the localhost:port with an actual IP and port address when I have node running.
My console returns this on the tab that is running node:
undefined
{ a: '1', b: '2', c: '3' }
And this on the tab where I typed the cURL command:
<!doctype html>
<html>
<head>
<title>Demo Page</title>
</head>
<body>
<h1>POST Request Received</h1>
<table>
<caption><p>Request Body Table</p></caption>
<thead>
<tr>
<th>Property Names</th>
<th>Values</th>
</tr>
</thead>
<tbody>
<tr>
<td>a</td>
<td>1</td>
</tr>
<tr>
<td>b</td>
<td>2</td>
</tr>
<tr>
<td>c</td>
<td>3</td>
</tr>
</tbody>
</table>
</body>
So everything seems to be working from the console but when I try to access localhost:port/request, I go to the 404 error instead of a page that displays the tables.
Can anyone tell me what I'm doing wrong? Thank you all for your time.

Using Ember Data to load data async from node sever

My Model :
App.Contacts = DS.Model.extend({
name : DS.attr('string'),
number : DS.attr('number')
});
This is how i save a record :
App.AddController = Ember.Controller.extend({
actions : {
addContact : function(){
var post = this.store.createRecord('Contacts',{
name : this.get('name') ,
number : this.get('number')
});
post.save();
}
}
});
Acc to Ember's offical guide, this would send a POST request to /Contacts , so to handle it, i used this in nodejs/expressjs
app.post('/contacts',function(req,res){
posts.push( req.body);
console.log(posts);
res.send({status: 'OK'});
});
Now i wish to retrieve it, into another template called all so i used :
App.AllRoute = Ember.Route.extend({
model : function(){
return this.store.find('Contacts');
},
setupController : function(controller,model){
controller.set('contactList',model);
}
});
Acc to Emberjs guides, model hook supports promises out-of-the-box . so i assumed this should work.
My template :
<script type="text/x-handlebars" id="all" >
Hello
<table>
{{#each contact in contactList}}
<tr>
<td>{{contact.name}} </td>
<td>{{contact.number}} </td>
</tr>
{{else}}
<tr><td>No contacts yet </td> </tr>
{{/each}}
</table>
</script>
Question
But the model returns nothing, i understand that this.store.find('Contacts') doesn't return a javascript array, but essentially and object , implimenting Ember.Enumerable
But on the server side, the posts is an javascript array, therefore there might be an type mismatch between then. how to resolve this?
EDIT:
To avoid any confusions in client side Ember code , This works properly, so there is some problem with the round trip to server.
App.AllRoute = Ember.Route.extend({
model : function(){
return this.store.all('Contacts');
},
setupController : function(controller,model){
controller.set('contactList',model);
}
});
If you could provide a jsfiddle, it be nice. I'm not sure whether contactList is defined or not and whether the alias for that controller is actually defined. So based on what I see, I think the problem is you're iterating over a controller that does not have the model properly defined.
I'd suggest trying to do:
{{#each}}
<tr>
<td>{{contact.name}} </td>
<td>{{contact.number}} </td>
</tr>
{{else}}
<tr><td>No contacts yet </td> </tr>
{{/each}}
If you really want to use the contactList controller, then you need to make sure that the App.AllController "needs" the contactListController.
App.ContactListController = Ember.ArrayController.extend({}) // needs to be an array controller
App.AddController = Ember.ArrayController.extend({
needs: ["contactList"], // controller's used within this controller
contactList: Ember.computed.alias("controllers.contactList"), // needed to iterate over the model how you're doing it.
Both of these solutions should work assuming your data is actually loaded in Ember Data. You might want to check the "data" tab on the ember-data console. If you don't have that browser extension installed, do it. It's incredibly useful.
If all else fails, try logging to verify expected values using {{log contactList}}
Good luck

Resources