How can I pass content to an element in clients html page? - javascript

I'm currently using Node.js to serve a webpage that takes in user inputs which are stored on a mongodb server. The web page also displays specified or all user inputs entered. I'm trying to figure how to pass the user inputs from node.js to the <p> element.
In my node.js file I am responding with the user data as a string like so:
response.writeHead(200, {"Content-Type": "text/plain"});
response.write(stringifyMongoDBCollection(user_data_collection));
response.end();
When I do this, this re-directs the client to display the content as text/plain which I expected. The next step is to update just the content of <p>. How can I do this? I thought about re-serving the entire html content with the new populated <p> but that would make all current user inputs disappear...
The user data would be a mongodb collection array and look like this:
[ { _id: 5dda17065f7e9b64282e7291,
date: 'Sat Nov 23 2019 21:37:10 GMT-0800 (Pacific Standard Time)',
field: '127' },
{ _id: 5dda18ecf330d521a035c444,
date: 'Sat Nov 23 2019 21:45:16 GMT-0800 (Pacific Standard Time)',
field: 125},
{ _id: 5dda1951f330d521a035c445,
date: 'Sat Nov 23 2019 21:46:57 GMT-0800 (Pacific Standard Time)',
field: '111' } ]

You could do something like this.
In Node section
res.status(200).send(stringifyMongoDBCollection(user_data_collection));
Client side
function getContent() {
$.ajax({
url: "https://jsonplaceholder.typicode.com/todos",
success: function (res) {
if (res) {
res = res.slice(0, 5); // limiting data to 5
var val = '';
res.forEach(todo => {
val += '<p><b>Title:</b>' + todo.title + ' <b>Completed:</b> ' + todo.completed + '</p>';
});
}
$("#content").html(val);
},
error: function () {
var val = '<p>Error in loading content</p>'
$("#content").html(val);
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="getContent()">Get Content</button>
<h1>Todo</h1>
<div id="content"></div>
References
jQuery ajax() Method
Node.js - Response Object
AJAX Introduction

Related

Unable to open any file from browser

i'm using file-saver package to download files. The downloading is not the issue it seems to be the opening of any file. I console.log file from the files function logic below and get this:
File {name: '5ece9322f34d050a92546892.jpeg', lastModified: 1641918175691, lastModifiedDate: Tue Jan 11 2022 16:22:55 GMT+0000 (Greenwich Mean Time), webkitRelativePath: '', size: 156, …}
lastModified: 1641918175691
lastModifiedDate: Tue Jan 11 2022 16:22:55 GMT+0000 (Greenwich Mean Time)
[[Prototype]]: Object
name: "5ece9322f34d050a92546892.jpeg"
size: 156
type: ".jpeg"
webkitRelativePath: ""
[[Prototype]]: File
I get the following error:
The file 5ece9322f34d050a92546892.jpeg could not be opened.It may be damaged or use a file format that Preview doesn’t recognise.
My code:
import { saveAs } from 'file-saver';
const files = ({url, fileName}) => {
const extension = url.slice(url.lastIndexOf('.'));
const handleDownloadDocument = (fileUrl, name, ex) => {
const file = new File([fileUrl], name, { type: ex });
return saveAs(file);
};
return(<div onClick={() => handleDownloadDocument(url, fileName, extension)}> download </div>);
};

angularjs - post specific elements of an array

I'm using nodejs, mongodb, angular and html to make a RESTful service. I'm new at this and I have some problems!
With the next code of the controller, I'm sending the variable "fp" to my database:
$http.post('/fplist', $scope.fp);
It works pretty well but "fp" value is:
fpdia: Wed Nov 01 2017
fphora: 00:00:00
fppilot:{_id: "59f06a0f907c783d6ccb8901", nombre: "Mike Ross", iden: "111222333A", rpasenable: "Phantom1", $$hashKey: "object:10"}
fprpas:{_id: "59f1b8bbdbae0a23208d0ad8", model: "Phantom1", serial: "4444-444-4444", plate: "123 TT", $$hashKey: "object:14"}
fptitulo:"Test"
And I just want to save "fp" like:
fpdia: Wed Nov 01 2017
fphora: 00:00:00
fppilot: Mike Ross
fprpas: 123 TT
fptitulo:"Test"
You have to create another json object:
So, before you do your http request you just have to do this:
var obj = {
fpdia: $scope.fp.fpdia,
fphora: $scope.fp.fphora,
fppilot: $scope.fp.fppilot.nombre,
fprpas: $scope.fp.fprpas.plate,
fptitulo: $scope.fp.fptitulo
}
$http.post('/fplist', obj);

FindRecord with Ember and MongoDB

I have been looking on the web for an answer to this but I have not been able to find one, maybe I am not asking the right questions but here it goes.
So Im building a CRUD webapp using express, mongodb and ember cli, so far I can save data to my mongodb database (/events/new) and display my events (events/all) however I seem to be stuck when accessing an individual event my ideal URL will be /events/:eventname...
I know i'm getting the right result from the server, and I am getting ONLY ONE, however in the ember console, my model shows all my records, plus I cant seem to render the actual content from my model to the screen. IF I happen to go localhost:300/event/XXXX my ember console shows two records the one I want and some sort of dummy one having XXXX as the ID and the rest of the fields are undefined... Do i need to create a new route to look for the single record? or is there a way to use the same route I defined to look for all my records in events/all ? How do i get the data displayed on the screen ? Why do i see all my records when I access /events/eventname ?
Am I following best practices here ?
Express:
app.get('/api/events', function(req,res) {
eventsModel.find({},function(err,docs) {
if(err) {
res.send({error:err});
}
else {
// we only want to display the current events,
// so we filter throught them and return
// only the current ones
var current = [];
var today = new Date();
var tomorrow = today.setDate(today.getDate() - 1);
docs.forEach(function(item){
if(item.date >= tomorrow){
// console.log('new');
current.push(item);
}
});
res.send({events:current});
console.log('/api/events');
}
});
});
app.get('/api/events/:name', function(req, res){
console.log(req.url);
console.log('/api/events/event');
eventsModel.findOne({name: req.params.name},function(err,docs) {
if(err) {
res.send({error:err});
}
else{
res.send({event:docs});
}
});
});
Ember Router.js
Router.map(function() {
this.route('events', function() {
this.route('new');
this.route('update');
this.route('all');
this.route('event', { path: ':name' });
});
});
Ember events.event Routes
export default Ember.Route.extend({
model: function(params) {
this.store.find('event', params.name);
}
});
Ember events.all Template
{{#if model}}
{{#each model as |event| }}
<h2>{{#link-to 'events.event' event.name}}{{event.name}}{{/link-to}}</h2>
<p>{{event.date}}</p>
<p>{{event.location}}</p>
<p>{{event.address}}</p>
<a href={{event.url}}>Read More</a>
{{/each}}
{{else}}
Ember events.event Template
{{#each model as |item|}}
{{item.name}}
{{/each}}
{{outlet}}
My server response when going to /events/eventname is:
{ _id: 55d317d23281dfb23e9ecaa8,
url: 'http://gmail.com',
timestamp: Tue Aug 18 2015 07:32:34 GMT-0400 (EDT),
description: 'Another Address',
address: '123 Street',
long: 34.234,
lat: 12.123,
zip: 'h4t3y5',
city: 'Here',
location: 'Somewhere',
date: Mon Aug 31 2015 20:00:00 GMT-0400 (EDT),
name: 'Two Words',
__v: 0 }
The data is accurate and it changes depending on the post I click on.
Thanks for your help!
Assuming that you're using the RESTAdapter, your server response is in the wrong format. You can read about the format it expects here, but your response should look something like this:
{
"event": {
"id": "55d317d23281dfb23e9ecaa8",
"timestamp": "Tue Aug 18 2015 07:32:34 GMT-0400 (EDT)",
...
}
}

meteor not printing any data

I have the following application and when I render data I am getting null or no data for the {{video}} tag even though data exists in the collection Can anyone help me find the mistake
routes.js
Router.route('/videos/:id', function () {
var item = Videos.find({_id: this.params._id});
this.render('VideoItem', { data:item});
});
video.html
<template name="VideoItem">
<div class="container">
<h3> Video Information</h3>
{{video}}
</div>
</template>
video object when Videos.find().fetch()
_id: "FEXm65hwZ9QWXFSY8"
created_at: Mon May 18 2015 14:22:59 GMT+0200 (CEST)
duration: 10000
video: "temp"
videourl: "http://google.com"
__proto__: Object
find returns a cursor. That would work if you were iterating over a set of videos with #each. In your case you want a specific video so you'd need to use findOne like this:
Router.route('/videos/:_id', function () {
this.render('VideoItem', {
data: function () {
return Videos.findOne(this.params._id);
}
});
});

Sending email from gmail api not received but shown in sent folder

I' m using gapi to send gmail. But if I send the mail to myself, it doesn't appear in my inbox. The most strange, it appears in the 'Sent' folder.
`
function sendMessage(email, callback) {
// Web-safe base64
var base64EncodedEmail = btoa(email).replace(/\//g,'_').replace(/\+/g,'-');
var request = gapi.client.gmail.users.messages.send({
'userId': 'me',
'message': {
'raw': base64EncodedEmail
}
});
request.execute(callback);
}
function send() {
var var to = 'znlswd#gmail.com',
subject = 'Hello World',
content = 'send a Gmail.'
var email = "From: 'me'\r\n"+
"To: "+ to +"\r\n"+
"Subject: "+subject+"\r\n"+
"\r\n"+
content;
sendMessage(email, function () {
console.log(arguments);
});
}
`
The information log in console is:
"[↵ {↵ "id": "gapiRpc",↵ "result": {↵ "id": "1471e09d88000bf7",↵ "threadId": "1471e09d88000bf7",↵ "labelIds": [↵ "SENT"↵ ]↵ }↵ }↵]↵"
And I can see this mail in the 'Sent' folder in Gmail, but I didn't get it in the inbox.
The original of this mail in the 'Sent' folder is as follow:
Received: from 823618323534-124pu7sujfj5olv94rkr0apqdppc6nti.apps.googleusercontent.com
named unknown
by gmailapi.google.com
with HTTPREST;
Wed, 9 Jul 2014 19:11:07 -0700
From: znlswd#gmail.com
To: znlswd#gmail.com
Subject: Hello World
Date: Wed, 9 Jul 2014 19:11:07 -0700
Message-Id: <CADOxe9KLTdYfcb8OxWz+rFSM4tVKuZcVV8HJ4byv95+qPA=+dw#mail.gmail.com>
send a Gmail.
Anybody knows why? Thanks very much!
Edit:
I change the 'To:' in Mime message to another mailbox(not Gmail), and receive the mail correctly. Feeling More confused.
Edit:
I add a 'Cc': field, It is : znlswd#gmail.com(myself), 71848140#qq.com, swdpal2014#gmail.com, ezdiary#163.com . All the other guys(Gmail and other mailboxs) received the mail, but I still couldn't receive the mail from myself.
The original mail I received in ezdiary#163.com is as follow:
Received: from mail-qg0-f44.google.com (unknown [209.85.192.44])
by mx42 (Coremail) with SMTP id XMCowEAJvlfC_L1TjzExBg--.81S3;
Thu, 10 Jul 2014 10:39:03 +0800 (CST)
Received: by mail-qg0-f44.google.com with SMTP id j107so7126918qga.31
for <ezdiary#163.com>; Wed, 09 Jul 2014 19:38:57 -0700 (PDT)
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
d=gmail.com; s=20120113;
h=mime-version:from:date:message-id:subject:to:cc:content-type;
bh=zgoFEkSzE1bUNp54umXlfaDEDw5bLf2Ei0uFrgrVZic=;
b=UHOLwuTsFL9yajR0nn/TskbhVKrIfzX4OAsNDno4S2QIvwx83H5dOe2WMyFbL6Plmk
n4z2qzGjturoi1411+PGpgj8rt4Y57aDQpu7tEOMolMmFLJomtCSmagHIHhc0qwU+CRL
rTjO2ztwZoj/ejnqwcmANzgzMMnSxxkcIf3OvXhLm+j+5yHQvPhmGWIapFWJaTN+9gb9
Q47Qkqe5dBrsxOnGhgQnr1orbE5NcLIYumZTH1YfCMZvqIjUtmviUQUKpfhNQD5UtCX0
0J2moKK98Q5Vek4Wti/WtnEqOgNTzHkIL1M90eeAJKelyPu4TQ7G9GJxr1FX+s4WhgrM
xTFA==
MIME-Version: 1.0
X-Received: by 10.224.137.9 with SMTP id u9mr78577439qat.24.1404959937414;
Wed, 09 Jul 2014 19:38:57 -0700 (PDT)
Received: from 823618323534-124pu7sujfj5olv94rkr0apqdppc6nti.apps.googleusercontent.com
named unknown by gmailapi.google.com with HTTPREST; Wed, 9 Jul 2014 19:38:56 -0700
From: znlswd#gmail.com
Date: Wed, 9 Jul 2014 19:38:56 -0700
Message-ID: <CADOxe9KF+VjMFw1bSkFd09RVsa7c7-pz9OguCFovOUemW4ZZbg#mail.gmail.com>
Subject: Hello World
To: znlswd#gmail.com
Cc: 71848140#qq.com, swdpal2014#gmail.com, ezdiary#163.com
Content-Type: text/plain; charset=UTF-8
X-CM-TRANSID:XMCowEAJvlfC_L1TjzExBg--.81S3
Authentication-Results: mx42; spf=pass smtp.mail=znlswd#gmail.com; dki
m=pass header.i=#gmail.com
X-Coremail-Antispam: 1Uf129KBjDUn29KB7ZKAUJUUUUU529EdanIXcx71UUUUU7v73
VFW2AGmfu7bjvjm3AaLaJ3UbIYCTnIWIevJa73UjIFyTuYvjxUSeT5DUUUU
send a Gmail.
Edit: the original mail in swdpal2014#gmail.com is as follow:
Delivered-To: swdpal2014#gmail.com
Received: by 10.194.121.101 with SMTP id lj5csp1399131wjb;
Wed, 9 Jul 2014 19:38:58 -0700 (PDT)
Return-Path: <znlswd#gmail.com>
Received-SPF: pass (google.com: domain of znlswd#gmail.com designates 10.224.137.9 as permitted sender) client-ip=10.224.137.9
Authentication-Results: mr.google.com;
spf=pass (google.com: domain of znlswd#gmail.com designates 10.224.137.9 as permitted sender) smtp.mail=znlswd#gmail.com;
dkim=pass header.i=#gmail.com
X-Received: from mr.google.com ([10.224.137.9])
by 10.224.137.9 with SMTP id u9mr68151154qat.24.1404959937949 (num_hops = 1);
Wed, 09 Jul 2014 19:38:57 -0700 (PDT)
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
d=gmail.com; s=20120113;
h=mime-version:from:date:message-id:subject:to:cc:content-type;
bh=zgoFEkSzE1bUNp54umXlfaDEDw5bLf2Ei0uFrgrVZic=;
b=UHOLwuTsFL9yajR0nn/TskbhVKrIfzX4OAsNDno4S2QIvwx83H5dOe2WMyFbL6Plmk
n4z2qzGjturoi1411+PGpgj8rt4Y57aDQpu7tEOMolMmFLJomtCSmagHIHhc0qwU+CRL
rTjO2ztwZoj/ejnqwcmANzgzMMnSxxkcIf3OvXhLm+j+5yHQvPhmGWIapFWJaTN+9gb9
Q47Qkqe5dBrsxOnGhgQnr1orbE5NcLIYumZTH1YfCMZvqIjUtmviUQUKpfhNQD5UtCX0
0J2moKK98Q5Vek4Wti/WtnEqOgNTzHkIL1M90eeAJKelyPu4TQ7G9GJxr1FX+s4WhgrM
xTFA==
MIME-Version: 1.0
X-Received: by 10.224.137.9 with SMTP id u9mr78577439qat.24.1404959937414;
Wed, 09 Jul 2014 19:38:57 -0700 (PDT)
Received: from 823618323534-124pu7sujfj5olv94rkr0apqdppc6nti.apps.googleusercontent.com
named unknown by gmailapi.google.com with HTTPREST; Wed, 9 Jul 2014 19:38:56 -0700
From: znlswd#gmail.com
Date: Wed, 9 Jul 2014 19:38:56 -0700
Message-ID: <CADOxe9KF+VjMFw1bSkFd09RVsa7c7-pz9OguCFovOUemW4ZZbg#mail.gmail.com>
Subject: Hello World
To: znlswd#gmail.com
Cc: 71848140#qq.com, swdpal2014#gmail.com, ezdiary#163.com
Content-Type: text/plain; charset=UTF-8
send a Gmail.
So to be clear, sending mail works as it sends correctly to others. In the case of sending mail to yourself (why exactly are you doing this? is this really needed as opposed to say just using messages.insert?) then it appears in only SENT but not also INBOX label. You only get one copy of the mail, that's the same irregardless of API or using web UI. The problem is that the web UI also puts that message in INBOX as well as SENT. (As you can tell, sending to yourself is a bit of a special case due to things like dupe-detection based on the Message-Id header, etc.)
Answer the question myself. First I tried using messages.insert. However, if I set the 'From' the same as the 'To'(my email address), the mail will still only be in the 'SENT' folder. the right way is using the message.modify api to add 'INBOX' and 'UNREAD' label to the mail sent.
gapi.client.request({
path: "gmail/v1/users/me/messages/" + messageid + "/modify",
method: "POST",
body: "{\"addLabelIds\": [\"UNREAD\",\"INBOX\"]}",
callback: function() {
console.log("gmail sent to self");
return console.log(arguments);
}
})
The 'messageid' refer to the id return by the send api.
An untested idea: you can try adding an X-Gmail-Labels: Inbox header to the messages.send REST call in hopes that Gmail will add the label. I saw this header when doing a Google Takeout of some labels in GMail to mbox files.

Categories

Resources