TypeError: Cannot read property 'text' of undefined - mongodb

router.post('/addtodo', (req, res, next) => {
let todo = new Todos({
text: req.body.text,
date: new Date(),
});
Todos.addTodo(todo, (err, todos, next) => {
if(err) throw err;
res.json(todos);
});
});
I am trying to save a document in the Todo schema using the above method
Schema and methods are as follows
const todoSchema = mongoose.Schema({
text: {
type: String
},
date: {
type: Date,
default: Date.now
}
});
const Todos = module.exports = mongoose.model('todos', todoSchema);
//Retrieve documents
module.exports.getTodos = (callback) => {
Todos.find(callback);
};
//Add document
module.exports.addTodo = (todo, callback) => {
Todos.create(todo, callback);
};
But when I try to POST a json object using postman it shows this error.
<body>
<pre>TypeError: Cannot read property 'text' of undefined
<br> at router.post (C:\Users\shahaji.shinde\Desktop\practice\todo-mean\router\todoroute.js:18:24)
<br> at Layer.handle [as handle_request] (C:\Users\shahaji.shinde\Desktop\practice\todo-mean\node_modules\express\lib\router\layer.js:95:5)
<br> at next (C:\Users\shahaji.shinde\Desktop\practice\todo-mean\node_modules\express\lib\router\route.js:137:13)
<br> at Route.dispatch (C:\Users\shahaji.shinde\Desktop\practice\todo-mean\node_modules\express\lib\router\route.js:112:3)
<br> at Layer.handle [as handle_request] (C:\Users\shahaji.shinde\Desktop\practice\todo-mean\node_modules\express\lib\router\layer.js:95:5)
<br> at C:\Users\shahaji.shinde\Desktop\practice\todo-mean\node_modules\express\lib\router\index.js:281:22
<br> at Function.process_params (C:\Users\shahaji.shinde\Desktop\practice\todo-mean\node_modules\express\lib\router\index.js:335:12)
<br> at next (C:\Users\shahaji.shinde\Desktop\practice\todo-mean\node_modules\express\lib\router\index.js:275:10)
<br> at Function.handle (C:\Users\shahaji.shinde\Desktop\practice\todo-mean\node_modules\express\lib\router\index.js:174:3)
<br> at router (C:\Users\shahaji.shinde\Desktop\practice\todo-mean\node_modules\express\lib\router\index.js:47:12)
<br> at Layer.handle [as handle_request] (C:\Users\shahaji.shinde\Desktop\practice\todo-mean\node_modules\express\lib\router\layer.js:95:5)
<br> at trim_prefix (C:\Users\shahaji.shinde\Desktop\practice\todo-mean\node_modules\express\lib\router\index.js:317:13)
<br> at C:\Users\shahaji.shinde\Desktop\practice\todo-mean\node_modules\express\lib\router\index.js:284:7
<br> at Function.process_params (C:\Users\shahaji.shinde\Desktop\practice\todo-mean\node_modules\express\lib\router\index.js:335:12)
<br> at next (C:\Users\shahaji.shinde\Desktop\practice\todo-mean\node_modules\express\lib\router\index.js:275:10)
<br> at expressInit (C:\Users\shahaji.shinde\Desktop\practice\todo-mean\node_modules\express\lib\middleware\init.js:40:5)
</pre>
</body>
The error is in the first code snippet- line number 3.

Two possible causes come to my mind with the information you posted:
- It can be because you are not sending the appropriate Content-Type: application/json (check it).
- Server is not ready to parser json:
For that, you should have something like this:
var bodyparser = require('body-parser');
app.use(bodyparser.urlencoded({ extended: true }));
app.use(bodyparser.json({limit: '10mb'}));
Let me know if it helps you

Related

Property or method "info" is not defined on the instance but referenced during render

I'm trying to display information coming from a rest API with Vue.js
In a component I want to display users...
<template>
<div>
<h1>User Manager</h1>
<p>
{{ users }}
</p>
</div>
</template>
In the script part :
<script>
import {AxiosInstance as axios} from "axios";
export default {
name: "User",
data(){
return{
users: null
}
},
methods: {
getUsers(){
axios.get("http://localhost:4000/api/users").then(response => {
console.log(response);
this.users = response.data;
});
}
},
mounted(){
this.getUsers();
}
}
</script>
<style scoped></style>
I obtain unfortunatelly an error message such as :
Error in mounted hook: "TypeError: Cannot read property 'get' of undefined"
TypeError: Cannot read property 'get' of undefined...

ReferenceError: " postIts.forEach(function(postit)" on list.ejs? postIts is not defined at eval (eval at compile

I need to loop through an object PostIts and display the "Id", " Title" with an ejs "forEach" Loop Am using sails.js "1.2.3" and mongodb on local host, but i get error
ReferenceError : postIts is not defined at eval (eval at compile ?
Here is the code on the PostItsController.js:
module.exports = {
list: function(req, res) {
// res.view('list');
PostIts.find({}).exec(function(err, postIts) {
if (err) {
res.send(500, { error: 'Database Error' });
}
res.view('list', { postIts: postIts });
});
}
};
And here is the code on list.ejs:
<tbody>
<% postIts.forEach(function(postit){ %>
<tr>
<td>
<%= postit.id %>
</td>
<td>
<%= postit.title %>
</td>
<td></td>
</tr>
<% }) %>
</tbody>
I should get the value of the ID and title displayed on the list.ejs page in a table, but instead I get an error that the postIts object is not defined.
First of all your route '/postIts/list': { view: 'list' }, should point to an action (since it has backend logic) not a view, so in your case "/postIts/list": "PostItsController.list", but if you're using actions2 things would be simpler
Secondly you don't need to tell your users that you have a database error error: "Database Error"
Using Actions2
sails generate action post/list
In your config/route.js
'POST /api/v1/post/list': { action: 'post/list' },
In your action
module.exports = {
friendlyName: "List Posts",
description: "List all post in our site",
inputs: {},
exits: {
success: {
description: "The path to your template file",
viewTemplatePath: "list"
}
},
fn: async function(inputs) {
var posts = await Post.find();
// All done.
return { postIts: posts };
}
};
postit works
An Boohoo! it works
https://sailsjs.com/documentation/concepts/actions-and-controllers/routing-to-actions
If you're sure that res.view('list', { postIts: postIts }); is actually sending the correct data you can use _.each(postIts, cb()) ... instead
For some reason the postIts object didnt save the data from the post req I made instead it just recalled what I posted. and I used the '_.each(postIts, function (postit)' and it finally worked.
to me its like a magic happened hahaha but yeah I learned from it.
thanks #Navicstein Rotciv for the quick replies.

Angular 2 : How to make POST call using form

I am completely new to Angular 2 and form concept. I am trying to POST form data to a POST API call. like this
POST API : http://localohot:8080/**********
Component :
user: any = {
id: null,
gender: null,
mstatus: null,
birthdate: null,
bloodgroup: null
}
userName: any = {
id: null,
personId: null,
displayName: '',
prefix: null,
givenName: null
}
userAddressJSON: any = {
id: null,
personId: null,
address1: null,
address2: null,
cityVillage: null
}
var form = new FormData();
form.append('userid', new Blob(['' + uid], { type: 'application/json' }));
form.append('user', new Blob([JSON.stringify(this.user)], { type: 'application/json' }));
form.append('userName', new Blob([JSON.stringify(this.userName)], { type: 'application/json' }));
form.append('userAddress', new Blob([JSON.stringify(this.userAddressJSON)], { type: 'application/json' }));
Here, I don't know how to make API call.
In our old application they used form data POST in jQuery. Now I am trying to do the same in Angular 2. When I do the form POST in old application they are sending like this
------WebKitFormBoundarybAWvwmP2VtRxvKA7
Content - Disposition: form - data; name = "userid"; filename = "blob"
Content - Type: application / json
------WebKitFormBoundarybAWvwmP2VtRxvKA7
Content - Disposition: form - data; name = "user"; filename = "blob"
Content - Type: application / json
------WebKitFormBoundarybAWvwmP2VtRxvKA7
Content - Disposition: form - data; name = "userName"; filename = "blob"
Content - Type: application / json
------WebKitFormBoundarybAWvwmP2VtRxvKA7
Content - Disposition: form - data; name = "userAddress"; filename = "blob"
Content - Type: application / json
Can any one help me how to do that form POST in Angular 2.
Here is how I currently make a POST call in my Angular 2 app, because it sounds like you could use a simple example of how to setup a form. Here is the Angular 2 documentation on How to Send Data to the Server.
For even more high level documentation on making AJAX requests in Angular 2 visit this URL.
in my app/app.module.ts
...
import { HttpModule } from '#angular/http';
...
#NgModule({
imports: [
...
HttpModule
...
],
declarations: [
...
],
providers: [ ... ],
bootstrap: [AppComponent],
})
export class AppModule { }
app/system-setup/system-setup.ts
export class SystemSetup {
system_setup_id: number;
name: string;
counter: number;
}
app/form-component/form.component.html (Notice the [(ngModel)], that is what binds the property of the object to the html input element)
<form class="form" (ngSubmit)="saveEdits()" #editSystemSetupForm="ngForm">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="theName" name="name" [(ngModel)]="selectedItem.name" #itemsName="ngModel" required minlength="3"/>
<div [hidden]="itemsName.valid || itemsName.pristine" class="alert alert-danger">Name is required! Min length of 3.</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="">Counter</label>
<input type="number" step=0.01 class="form-control" name="counter" [(ngModel)]="selectedItem.counter" />
</div>
</div>
</div>
<div class="row">
<div class="col-md-4 col-md-offset-8">
<button type="submit" class="btn btn-success" style="float: right; margin-left: 15px;" [disabled]="!editISystemSetupForm.form.valid" >Save</button>
<button type="button" class="btn btn-danger" style="float: right;" (click)="cancelEdits()">Cancel</button>
</div>
</div>
</form>
in my app/form-component/form.component.ts
import { Component, OnInit, Input, Output, EventEmitter } from '#angular/core';
import { Headers, RequestOptions, Http, Response } from '#angular/http';
import { SystemSetup } from '../system-setup/system-setup';
#Component({
selector: 'app-setup-form',
templateUrl: 'setup-form.component.html',
styleUrls: ['setup-form.component.css']
})
export class SetupFormComponent implements OnInit {
#Input() selectedItem: SystemSetup; // The object to be edited
#Output() finishedEditing = new EventEmitter<number>(); // When the POST is done send to the parent component the new id
// Inject the Http service into our component
constructor(private _http: Http) { }
// User is finished editing POST the object to the server to be saved
saveEdits(): void {
let body = JSON.stringify( this.selectedItem );
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this._http.post('http://localhost:8080/**********', body, options)
.map(this.extractData)
.do(
data => {
this.finishedEditing.emit(data.system_setup_id); // Send the parent component the id if the selectedItem
})
.toPromise()
.catch(this.handleError);
}
/**
* Gets the data out of the package from the AJAX call.
* #param {Response} res - AJAX response
* #returns SystemSetup - A json of the returned data
*/
extractData(res: Response): SystemSetup {
let body = res.json();
if (body === 'failed') {
body = {};
}
return body || {};
}
/**
* Handles the AJAX error if the call failed or exited with exception. Print out the error message.
* #param {any} error - An error json object with data about the error on it
* #returns Promise - A promise with the error message in it
*/
private handleError(error: any): Promise<void> {
// In a real world app, we might use a remote logging infrastructure
// We'd also dig deeper into the error to get a better message
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Promise.reject(errMsg);
}
}
This URL is the link to the official Angular 2 documentation site, which is a very good reference for anything an Angular 2 developer could want.

How to fix TypeError: Cannot read property 'name' from Express Nodemailer

So I do want to say that I've been searching for the answer for this and I've also tried to console.log my req.body post form and I keep getting undefined. So I feel that I'm losing the data from the form I send, I'm not sure what I"m doing wrong. So time to show some code.
As a note: I am using Handlebars for my Express Setup.
app.js
var express = require('express'),
exphbr = require('express3-handlebars'), // "express3-handlebars"
nodemailer = require('nodemailer'),
helpers = require('./lib/helpers'),
app = express(), handlebars;
// Create `ExpressHandlebars` instance with a default layout.
handlebars = exphbr.create({
defaultLayout: 'main',
helpers : helpers,
extname : '.html',
// Uses multiple partials dirs, templates in "shared/templates/" are shared
// with the client-side of the app (see below).
partialsDir: [
'views/shared/',
'views/partials/'
]
});
// Register `hbs` as our view engine using its bound `engine()` function.
app.engine('html', handlebars.engine);
app.set('view engine', 'html');
require("./routes")(app, express, nodemailer);
app.listen(3000);
routes.js
module.exports = function (app, express, nodemailer) {
// set up the routes themselves
app.get('/', function (req, res) {
res.render('home', {
title: 'Larry King Orchestra'
});
});
// I cut out a majority of my routes to make this easier to read.
// SEND EMAIL FROM FORM
app.post('/', function (req, res) {
console.log("WTF");
console.log(req.body.name);
console.log(req.body.email);
var mailOpts, smtpTrans;
//Setup nodemailer transport, I chose gmail. Create an application-specific password to avoid problems.
smtpTrans = nodemailer.createTransport('SMTP', {
service: 'Gmail',
auth: {
user: "email#gmail.com",
pass: "password"
}
});
//Mail options
mailOpts = {
from: req.body.email, //grab form data from the request body object
to: 'anotheremail#gmail.com',
subject: 'LKO Contact Form',
html: 'From: ' + req.body.name + ' <' + req.body.email + '> <br>Phone: ' + req.body.tel + '<br>Date of Event: ' + req.body.date + '<br>Location: ' + req.body.location + '<br>Details & Comments:<br>' + req.body.message + '<br><br><p>Email form provided by WavaMedia.'
};
smtpTrans.sendMail(mailOpts, function (error, response) {
//Email not sent
if (error) {
res.render('home', {
title: 'Larry King Orchestra',
msg: 'Error occured, message not sent.',
err: true,
page: 'home'
});
}
//Yay!! Email sent
else {
res.render('home', {
title: 'Larry King Orchestra',
msg: 'Message sent! Thank you.',
err: false,
page: 'home'
});
}
});
});
// STATIC ROUTE FOR ASSESTS
app.use(express.static('assests/'));
};
I renamed the handlebars extension to be .html and I have the main layout using partials. SO app.get('/') will show this next file as a partial, and render it on the page.
contact.html
<form class="contact" action="/" method="post">
<label for="name">Name</label>
<input type="name" name="name" id="name">
<label for="email">Your Email (required)</label>
<input type="email" name="email" id="email">
<label for="tel">Phone Number</label>
<input type="tel" name="tel" id="tel">
<label for="date">Date of Your Event</label>
<input type="date" name="date" id="date">
<label for="location">Venue/Location</label>
<input type="location" name="location" id="location">
<label for-"message">Details & Comments</label>
<textarea name="message" id="message" rows="3"></textarea>
<input type="submit" name="submit" id="submit" value="Send" class="btn btn-default">
</form>
My Error:
TypeError: Cannot read property 'name' of undefined at c:\xampp\htdocs\lko\routes.js:129:26 at callbacks (c:\xampp\htdocs\lko\node_modules\express\lib\router\index.js:164:37) at param (c:\xampp\htdocs\lko\node_modules\express\lib\router\index.js:138:11) at pass (c:\xampp\htdocs\lko\node_modules\express\lib\router\index.js:145:5) at Router._dispatch (c:\xampp\htdocs\lko\node_modules\express\lib\router\index.js:173:5) at Object.router (c:\xampp\htdocs\lko\node_modules\express\lib\router\index.js:33:10) at next (c:\xampp\htdocs\lko\node_modules\express\node_modules\connect\lib\proto.js:193:15) at Object.expressInit [as handle] (c:\xampp\htdocs\lko\node_modules\express\lib\middleware.js:30:5) at next (c:\xampp\htdocs\lko\node_modules\express\node_modules\connect\lib\proto.js:193:15) at Object.query [as handle] (c:\xampp\htdocs\lko\node_modules\express\node_modules\connect\lib\middleware\query.js:45:5)
So I'm not sure where I'm going wrong with the code. I believe the form is sending data to my node app, but where it's going, I'm not sure. I've setup the post method and so far no luck :( I have been trying for a couple days now. I have nodemailer installed as well. I've restarted the server, updated node and npm.
JavaScript Node Guru Masters, only you can show me the light! And thanks for reading though all of this, totally awesome!
app.use(express.bodyParser());
add that to your app.js
that's what grabs information from the post data form.
You have to require body parser package for this.
At first you have to install it with npm.
$ npm install --save body-parser
Then require that in your js file.
var bodyParser = require('body-parser');
Then add the parser. As you are using html post method it uses urlencoded as encoding type. For that add this line.
var urlencodedParser = bodyParser.urlencoded({ extended: false });
(If you use json you must use bodyParser.json() instead of this)
Now add the parser with the encoding type to app.post method as follows.
app.post('/',urlencodedParser, function (req, res) {
//your code here
});
You don't have to be explicitly mention any bodyParser or bodyParer.json
Instead You can make it simple to use this because this is a built-in middleware function in Express.
app.use(express.json());
app.use(bodyparser.urlencoded({extended : true }));

angularjs $resource : can't $save JSON

starting with angular, i am trying to GET data from the server and then POST back modifications with $resources.
It's working fine except the "save" function. No Data is POSTed back to the server.
here is the html
<div ng-controller="myCtrl">
<div ng-repeat="obj in objs">
<h2>{{obj.data_1}}</h2>
<h3>{{obj.data_2}}</h3>
<input type='text' ng-model="obj.data_1"><br/>
<textarea ng-model="obj.data_2" required></textarea><br/>
<button ng-click="save()">Save</button>
</div>
</div>
service.js
'use strict';
angular.module('App.services', ['ngResource']).
factory('Obj', function($resource){
return $resource('url/to/json');
});
controller.js:
'use strict';
angular.module('App.controllers', []).
controller('myCtrl', ['$scope', 'Obj', function($scope, Obj) {
$scope.objs = Obj.query();
$scope.save = function() {
$scope.objs.save();
}
}]);
Do you know why nothing is POSTed back when i save ?
Using the query method on the $resource object implies return as follows 'query': {method:'GET', isArray:true} it's mean that your $scope.objs is an array of objects and not an object and depending on number of elements you can use the folowing notation:
$scope.objs[i].save()
where i is the index of element in the array, forexample if you have return like:
[ {id:1, name:'Some name', age:35} ];
then your code : $scope.objs[0].save()
Edit:
I have created a plunk, maybe it will help you... http://plnkr.co/edit/62iPCAUNjV0oJROhul1G
Shouldn't there be another $resource declared for POST the way it is declared for GET? Each $resource specify particular REST service.
//services.js
'use strict';
angular.module('App.services', ['ngResource'])
.factory('GetObj', function($resource){
return $resource('url/to/json');
}
.factory('SaveObj', function($resource){
return $resource('url/to/post');
});
//controller.js
'use strict';
angular.module('App.controllers', []).
controller('myCtrl', ['$scope', 'GetObj', 'SaveObj', function($scope, GetObj, SaveObj) {
$scope.objs = Obj.query();
$scope.save = SaveObj.save(objs, function(resp) {
//Callback
console.log("Response from POST: %j", resp);
}
}]);