Error: Reference.set failed: First argument contains undefined in property - node.js

I'm trying to test a POST method in a Nodejs/express application. I've connected to the firebase database.
My question is mainly related to the error. What am I doing wrong and how can I fix this please?
This is the error report:
PS C:\Users\WorkoutApp_v1> node app.js
Server started on port: 3000
Error: Reference.set failed: First argument contains undefined in property 'workouts.-Lqkqtcf6e2RED2F_1av.name'
This is the workout.js file with POST method.
const express = require('express');
const router = express.Router();
const firebase = require('firebase');
router.get('/add', function(req,res,next) {
res.render('workouts/add');
});
router.post('/add', function(req,res,next) {
var workout = {
name: req.body.name,
discription: req.body.discription,
set: req.body.set,
repsTime: req.body.repsTime
}
// console.log(workout);
// return;
// const fbRef = firebase.database().ref();
// var dbRef = fbRef.child('workouts');
// dbRef.push().set(workout);
// alternative implementation of the above 3-lines
firebase.database().ref().child('workouts').push().set(workout);
req.flash('success_msg', 'Workout saved');
res.redirect('/workouts');
});
module.exports = router;
This is the add.ejs file.
<form method="post" action="/workouts/add">
<div class="form-group">
<label>Exercise</label>
<input type="text" class="form-control" name="name" placeholder="Workout Name">
<label>Description</label>
<input type="text" class="form-control" name="description" placeholder="Description">
<label>Set</label>
<input type="text" class="form-control" name="sets" placeholder="Number of sets">
<label>RepsTime</label>
<input type="text" class="form-control" name="repsTime" placeholder="Number of repsTime">
</div>
<button type="submit" class="btn btn-default">Submit</button>
<a class="btn btn-danger" href="/workouts">Close</a>
</form>

The value undefined can't be written in RTDB.
The value undefined is what you get when you access object properties that don't exist.
Your req.body.name is undefined because req.body doesn't have a name property.
What does your commented-out console.log(workout) print?
When you write code that might lead to writing undefined in RTDB, you should replace it with something else. In this scenario, you could use req.body.name || '', to replace a missing name property with an empty string.
In general, using || can cause trouble, because values like 0 and '' are equivalent to false, so they would be replaced by your default value.
A safer thing to do is value === undefined ? defaultValue : value.

Related

How to get Express route's body parameters as 'string' instead of 'any' in Typescript?

I'm sending a string productId using a hidden input type through a <form>:
<form action="/cart" method="POST">
<button class="btn" type="submit">Add to Cart</button>
<input type="hidden" name="productId" value="<%= product.id %> "> // EJS template engine
</form>
And then receiving the productId in an Express route as follows:
export const postCart = async (request: Request, response: Response): Promise<void> => {
const productId = request.body.productId // This is inferred as type 'any'
const allProducts = //...Array<Product>
const requestedProduct = allProducts.find((product) => product.id === productId) // Problem: this is always false
}
Problem
The condition product.id === productId is always false because the type of product.id from the database is string and type of productId received from the body is any. I need a way for both of them to be of same type.
What I tried so far
I tried annotating and casting the type of productId:
const productId: string = request.body.productId // Doesn't work
const productId: string = request.body.productId as string // Doesn't work
const productId: string = request.body.productId + '' // Doesn't work
The only thing that works is, if I create the Numbers from the ids:
Number(product.id) === Number(productId)
But this can't be a solution because I'm using UUID strings for representing the product id. And casting UUIDs to the numbers may not be a good idea.
Any input would be much appreciated.
So we chatted out in the comment section but the problem seems to have been the trailing space in the html:
<input type="hidden" name="productId" value="<%= product.id %> ">
updated to:
<input type="hidden" name="productId" value="<%= product.id %>">

Passing a variables value in post request node express

Simple issue - I have a node express app that I want to perform a post request - using request passing the value of a string variable.
I don't want to transfer the name of the variable but its value.
If I just add the name to the query it will pass the actual name.
Looking forward for a solution.
Here is how your html file will look:
<form method='POST' action="/signup">
<b>USERNAME:</b> <input type="text" name="userName" placeholder="yourname">
<br>
<br>
<b>PASSWORD:</b> <input type="password" name="userPass" placeholder="***"><br>
<br>
<b>CONF. PASS.:</b> <input type="password" name="cnfPass" placeholder="***"><br>
<br>
<input type="submit" class = 'btn btn-primary' value="Signup">
</form>
Here is how your js file will look:
app.post('/signup',urlencodedparser,function(req,res){
var uPass=req.body.userPass;
var uName=req.body.userName;
var cnfPass = req.body.cnfPass;
if(uPass!=cnfPass)
res.end('Passwords dont match!')
else
{
con.query("INSERT INTO USERS(name,password) values (?,?)",[uName,uPass])
res.sendfile('user.html')
}
}
)
You can fetch the values of the variables by assigning name to them in the html file.
In this case,
I obtain the input name value with help of 'userName' and 'userPass' fields.

i have insert all data in input every time i want update some value

i new using Angular and nodejs with mongodb
my problem its i have to insert all data again every time i want update my data
the value appers correctly in my form but if not insert again the all data the input the data not change its update null
my code
my editcliente.html
<input type="text" class="form-control" style="width:34px;height:34px" value="{{id}}" readonly>
<div class="form-group">
<label for="Name"> Name of Customor</label>
<input type="text" class="form-control" formControlName="Name" value="{{name}}">
</div>
<div class="form-group">
<label for="Address"> Address</label>
<input type="text" class="form-control" formControlName="Address" value="{{address}}">
</div>
my cliente.ts
registerUser(id:any){
let name = this.registerForm.value.Name;
let address= this.registerForm.value.Address;
let telephone = this.registerForm.value.Telephone;
let postalcode = this.registerForm.value.PostalCode;
let email = this.registerForm.value.email;
this.myfirstService.getupdate(id,name,address,telephone,postalcode,email).subscribe(data=>{
if(data.success){
console.log("deu")
}
else{
console.log(" nao deu")
}
})
}
app.post('/api/updateCliente',async (req,res)=>{
const {id,name,address,telephone,postalcode,email}= req.body
console.log(id,name,address,telephone,postalcode,email);
const resp = await Clientes.findOne({_id:id})
if(!resp){
res.json({
sucess:false,
message:'invalid cliente'
});
return
}
else{
await Clientes.updateOne({_id:id},{$set:{
name:name,
address:address,
email:email,
telephone:telephone,
postalcode:postalcode}})
res.json({
sucess:true
});
}
})
how i fix this problem
updateOne works on a retrieved document, i.e. your resp that was returned by Clientes.findOne.
Try something like:
resp.updateOne({
name:name,
address:address,
email:email,
telephone:telephone,
postalcode:postalcode})

Cannot read property toLowerCase of undefined using Adonis and PostgreSQL

I'm using Adonis with PostgreSQL and I am trying to implement a search where a user would be able to search through posts using the title
I have my code structured like so
<form action="{{ route('search') }}" method="GET" style="outline:none">
<input class="shadow appearance-none border-2 p-2 h-10" style="outline:none" type="text" name="q" placeholder="Search the forum" value="{{ request.input('q', '') }}">
</form>
and my controller like so
'use strict'
const Post = use('App/Models/Post')
const Database = use('Database')
class SearchController {
async index ({ view, request, response, params }) {
let posts = await Post.query()
.forIndex()
.whereRaw('lower(title) LIKE ?', params.searchString.toLowerCase())
.paginate(request.input('page', 1), 10)
return view.render('index', {
posts
})
}
}
module.exports = SearchController
However, I am getting the following error:
Instead of name='q' try name='searchString' in the form
See https://adonisjs.com/docs/4.1/request#_methods to get query string parameters in adonis

React - this._onSubmit not working

I am making a simple web app, using node, express and react. My routes are working fine and i am able to render my views, but the "events" in my views are not working.
The following view gets rendered but its events don't work.
var React = require('react');
var DefaultLayout = require('./layout/master');
var GeneralHtml = require('./generalhtml');
var ReactDOM = require('react-dom')
var SignupComponent = React.createClass({
getInitialState: function(){
  console.log('getInitialState');
return {}
    },    
_onSubmit: function (e){
  console.log('hello _onSubmit');
  },
_onChange: function(){
  console.log('hello _onChange');
  },
  render: function(){  
      return(
         <DefaultLayout name={this.props.name}>
        <form ref='sugnup_form' onSubmit={this._onSubmit}>
            <div className="col-md-5">
          <p className="h3">Signup Form</p>
          <GeneralHtml placeholder="Enter Your Name" name="user_name" onChange={this._onChange}>User Name</GeneralHtml>
          <GeneralHtml placeholder="Enter Your Email" onChange={this._onChange} name="email">Email</GeneralHtml>
          <GeneralHtml placeholder="Enter Your Password" name="password">password</GeneralHtml>
          <input className="btn btn-success" type="submit" value="Submit" onSubmit={this._onSubmit} />
          </div>
        </form>
           </DefaultLayout>
    )
  }
});
module.exports = SignupComponent;
The _onSubmit and _onChange events never get called. However, getInitialState is called.
What am i doing wrong here?
You won't get answers to this because your code works fine (I just removed the custom elements):
https://jsfiddle.net/ferahl/4x34ae37/
var SignupComponent = React.createClass({
getInitialState: function(){
  console.log('getInitialState');
return {}
    },    
_onSubmit: function (e){
  console.log('hello _onSubmit');
  },
_onChange: function(){
  console.log('hello _onChange');
  },
  render: function(){  
      return(
        <form ref='sugnup_form' onSubmit={this._onSubmit}>
            <div className="col-md-5">
<p className="h3">Signup Form</p>
<input placeholder="Enter Your Name" name="user_name" onChange={this._onChange}/>
<input placeholder="Enter Your Email" onChange={this._onChange} name="email"/>
<input placeholder="Enter Your Password" name="password"/>
<input className="btn btn-success" type="submit" value="Submit" />
</div>
        </form>
    )
  }
});
ReactDOM.render(
<SignupComponent />,
document.getElementById('container')
);
getInitialState must return an object otherwise it throws an error, which most likely is the reason your code isn't working.
Furthermore the input field does not have an onSubmit event attached to it so
won't work. Change it to onClick and it'll work.

Resources