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.
Related
i am created the search part using angular and node js. i have tested through the postman it is working fine. when connect with frond end anqular application is it not working error displayed
Failed to load resource: the server responded with a status of 404 (Not Found)
what i tried so far i attached below please check.
i tried on the url http://localhost:9001/user/findOne?first_name=kobinath
this is working well on postman but tested through the anqular didn't work. i attached the code what i tried so far.
employee.component.ts
search()
{
let name= {
"first_name" : this.first_name
};
this.http.post("http://localhost:9001/user/findOne",name).subscribe((resultData: any)=>
{
console.log(resultData);
});
}
employee.component.html
<form>
<div class="form-group">
<label>First Name</label>
<input type="text" [(ngModel)]="first_name" [ngModelOptions]="{standalone: true}" class="form-control" id="name" placeholder="Enter Name">
</div>
<button type="submit" class="btn btn-primary mt-4" (click)="search()" >Search</button>
</form>
</div>
What I noticed: With Postman you send first_name as a query parameter, but in your Angular-code you attach it to the request-body.
To achieve the equivalent of what you do in Postman, you could use the following code:
search(firstName: string) {
const params = new HttpParams().set('first_name', firstName);
const body = {
first_name : firstName
};
this.http.post("http://localhost:9001/user/findOne", body, { params: params })
.subscribe((resultData: any)=>
{
console.log(resultData);
});
}
Btw: Why don't you use GET instead of POST?
I am creating a simple todolist using react js and node js without database (to store data in objact array) I need to delete elements one by one by clicking. For each element I have Delete button. now todo list delete from front end(react), how to delete it from node any one please help me
todo.js
function Remove(id) {
const updateTodos=[...tasks].filter((obj)=>obj.id!==id)
setTasks(updateTodos)
}
if(isLogged){
return (
<div >
<h1>ToDo List</h1>
<form onSubmit={HandleSubmit}>
<input type="text" placeholder=" Add item..." name="list" value={toDos} onChange={(e)=>setToDos(e.target.value)}/>
<button id="btn" type="submit">Add</button>
</form>
<ul>
{tasks.map(obj=><li key={obj.id}>{obj.toDo}<button type='delete' onClick={(e)=>Remove(obj.id)} >Delete</button>
<input type="checkbox" id="" name=""onChange={(e)=>{
console.log(e.target.checked)
console.log(obj)
setTasks(tasks.filter(obj2=>{
if(obj2.id===obj.id){
obj2.status=e.target.checked
}
return obj2
}))
}} value={obj.status} /> </li>)}
</ul>
<h4>Completed tasks</h4>
{tasks.map((obj)=>{
if(obj.status){
return(<h5>{obj.toDos}</h5>)
}
return null
})}
</div>
);
}
}
export default Todo;
node- index.js
const lists =[
{id: new Date(),toDo:"learn react"}
]
app.post('/Todo',function(req, res){
lists.push({"id":new Date(),"toDo":req.body.list,"status":false})
console.log(lists)
res.status(200).json(lists[lists.length-1])
})
app.get('/Todo', (request, response) => response.status(200).json(lists));
req.body.list.pop()
res.status(200).json({"id":new Date(),"toDo":req.body.list,"status":false})
This will remove the last element in the list
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.
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})
I am using underscore temperating in jade.
index.jade
extends layout
block content
.wrap
.container-fluid#container
script(type='text/template' id='main-template')
.row
.col-xs-8.col-sm-9
.heading h2 Welcome to the Node Chatroom
hr/
.content
ul.list-group#chatList
.col-xs-4.col-sm-3
.sidePanel
.panel-heading
h3.panel-title Online Users
span.badge pull-right#userCount
hr/
.panel-body
ul.list-group#userList
.push
.footer
.container-fluid
.row
form
.form-group
.col-xs-8.col-sm-9
input(type="text" id="chatInput" class="form-control input-lg" placeholder="Write a message here..." rows="3")
.col-xs-4.col-sm-3
button(id="send-message-btn" class="btn btn-primary btn-lg btn-block" type="submit") Send Message
script(type='text/template' id='login-template')
.row
.col-md-4.col-md-offset-4.text-center
.login
.form-group
label Enter name
input(type="text" class="form-control" id="nameText")
.btn-group
button(id="name" type="button" class="btn btn-primary btn-lg") Login
Main.js
var LoginView = Backbone.View.extend({
template: _.template($('#login-template').html()),
events: {
'click #name': 'onLogin'
},
initialize: function(options) {
this.vent = options.vent;
this.listenTo(this.model, "change:error", this.render, this);
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
onLogin: function() {
//this.l.start();
this.vent.trigger("login", this.$('#nameText').val());
}
});
It is showing TypeError: n is undefined on line template: _.template($('#login-template').html()),
I have tried using . after script as proposed in jade doc . but it didn't work.
Looks like underscore cant access the #login-template id. Any reason why?
I was also getting same error. Then below one solved me.
var template= _.template($('#myTemplate').html());
This may help you.
typeerror-n-is-undefined-in-underscore-min-js