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);
Related
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
I have a function that fires and receives the e.target.files object but I cannot get the length of it. console.log(e.target.files.length) does not even fire.
<input multiple onChange={(e) => { this.handlefileupload(e) }} type="file" id="file" style={{ display: "none" }} />
this.handlefileupload = (e) => {
console.log(e.target.files)
console.log(e.target.files.length)
}
console.log(e.target.files) gives:
FileList {0: File(7105138), 1: File(7105138), 2: File(16792776), length: 3}0: File(7105138) {name: "image1.jpg", lastModified: 1544552208803, lastModifiedDate: Tue Dec 11 2018 10:16:48 GMT-0800 (Pacific Standard Time), webkitRelativePath: "", size: 7105138, …}1: File(7105138) {name: "imge2.jpg", lastModified: 1544468259102, lastModifiedDate: Mon Dec 10 2018 10:57:39 GMT-0800 (Pacific Standard Time), webkitRelativePath: "", size: 7105138, …}2: File(16792776) {name: "image3.png", lastModified: 1544558528903, lastModifiedDate: Tue Dec 11 2018 12:02:08 GMT-0800 (Pacific Standard Time), webkitRelativePath: "", size: 16792776, …}length: 3__proto__: FileList
Snapshot of console.log(e.target.files) as requested
I run a sample similar to your code, it seems like nothing is broken and actually I could get the length.
https://codesandbox.io/s/0m087x84vw
You might need to provide more code to help us detect where is the problem
It looks like you might of meant to type console.log(e.target.files.FileList.length) .
I have RESTfull service that produces and consumes JSON object
{
firstName: "Alex",
lastName: "Ross",
studentGroup: {
groupId: 1,
groupName: "java 15-1"
},
admissionDate: "2015-03-25",
status: {
statusId: 3,
statusName: "expelled"
},
term: {
termId: 4,
termName: "fourth"
},
id: 1
}
Here is admissionDate field which coresponds to input with type="date" on html page (page services to update object... so it should display current value and commit new one from date picker to RESTfull service):
<input required type="date" ng-model="student.admissionDate">
So, before representation of current value I converted its String value to date:
$scope.student.admissionDate = new Date(student.admissionDate);
Input produces date like - 'Fri Mar 11 2016 14:36:29 GMT+0200 (FLE Standard Time)'. BUT service doesn't recognize this format, expected is 'yyyy-MM-dd' format.
To avoid errors I use angular filter like
student.admissionDate = $filter('date')($scope.student.admissionDate, "yyyy-MM-dd");
Object can be send to server as well (PUT: /student) but in Chrome developer console I can observe error - "[ngModel:datefmt]" because the value format has been changed in <input> tag.
How can I solve this problem? What changes should be made to suit both Server format ('yyy-MM-dd') and angular validation in <input type="date">
I think the value you are passing to the filter is a string. You need to do new Date('the_date_string') before passing it to the filter.
That might work.
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)",
...
}
}
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.