i want tp Fetch POST data into mongodb cluster from a REACT FORM ,
how to extract value of inputs by name and get them into the post method ?
because i used req.body.NAME ... but it does not work
class Formulaire extends Component {
constructor(props) {
super(props)
}
addProduct = () => {
fetch('http://localhost:2904/addproduct' , {
method : 'POST',
body : JSON.stringify({
image :req.body.image ,
name :req.body.name,
price : req.body.price
}),
headers : {
'Content-type' : 'application/json'
}
})
}
render() {
return (
<div className = "formualire">
<form onSubmit = {this.addProduct}>
<input type="text" name="image" /> <br/>
<input type="text" name="name" /> <br/>
<input type="number" name="price" /> <br/>
<button type="submit">Post</button>
</form>
</div>
);
}
}
import React from 'react'
import { useForm } from "react-hook-form";
import { withRouter } from 'react-router-dom';
function Formulaire(props) {
const { register, handleSubmit } = useForm();
const addProduct = (data) => {
fetch('http://localhost:2904/addproduct', {
method: 'POST',
body: JSON.stringify({
image: data.image,
name: data.name,
price: parseInt(data.price)
}),
headers: {
'Content-type': 'application/json'
}
})
}
const aa =(data) => {
console.log(parseInt(data.price))
}
return (
<div className="formualire">
<form onSubmit={handleSubmit(addProduct)}>
<input type="text" {...register('image', { required: true })} /> <br />
<input type="text" {...register('name', { required: true })} /> <br />
<input type="number" {...register('price', { required: true })} /> <br />
<input type="submit" />
</form>
</div>
);
}
export default Formulaire;
Related
//it's an application that does the same job as uber eat..
import React from 'react';
import { NavLink } from 'react-router-dom';
import '../styles/Test.css';
class Test extends React.Component {
userData;
constructor(props) {
super(props);
this.state = {
fullName: ""
};
this.state = {
numero: "0"
};
this.state = {
rue: ""
};
this.state = {
numM: "0"
};
this.state = {
numb: "0"
};
this.state = {
code: "0"
};
this.state = {
commune: ""
};
}
handleSubmitForm(event) {
if (window.confirm(("Nom : " + this.state.fullName + "\rNombre de Repas : " + this.state.numero
+ "\rRue : " + this.state.rue + "\rNuméro de maison : " + this.state.numM
+ "\rNuméro de boite : " + this.state.numb + "\rCode postal : " + this.state.code +
"\rCommune : " + this.state.commune))) {
window.open("exit.html", "Thanks for Visiting!");
}
event.preventDefault();
}
handleChange(event) {
var value = event.target.value;
this.setState({
fullName: value
});
}
handleChange2(event) {
var value = event.target.value;
this.setState({
numero: value
});
}
handleChange3(event) {
var value = event.target.value;
this.setState({
rue: value
});
}
handleChange4(event) {
var value = event.target.value;
this.setState({
numM: value
});
}
//it's an application that does the same job as uber eat..
handleChange5(event) {
var value = event.target.value;
this.setState({
numb: value
});
}
handleChange6(event) {
var value = event.target.value;
this.setState({
code: value
});
}
handleChange7(event) {
var value = event.target.value;
this.setState({
commune: value
});
}
componentWillUpdate(nextProps, nextState) {
localStorage.setItem('user', JSON.stringify(nextState));
}
render() {
return (
<div className='formulaire'>
<center>
<form name='test2' onSubmit={this.handleSubmitForm} >
<fieldset>
<label>
Nom* :
<input
type="text"
value={this.state.fullName || ""} required
onChange={event => this.handleChange(event)}
/>
</label>
<label>
Nombre de Repas:
<input
type="number"
value={this.state.numero || ""} min={1} max={20}
onChange={event => this.handleChange2(event)}
/>
</label>
<label>
Rue*:
<input
type="text"
value={this.state.rue || ""} required
onChange={event => this.handleChange3(event)}
/>
</label>
<label>
Numéro de maison:
<input
type="number"
value={this.state.numM || ""}
onChange={event => this.handleChange4(event)}
/>
</label>
<label>
Numéro de boite:
<input
type="number"
value={this.state.numb || ""}
onChange={event => this.handleChange5(event)}
/>
</label>
<label>
Code:
<input
type="number"
value={this.state.code || ""} min={1000} max={9999}
onChange={event => this.handleChange6(event)}
/>
</label>
<label>
Commune:
<input
type="text"
value={this.state.commune || ""}
onChange={event => this.handleChange7(event)}
/>
</label>
<p> <input type="submit" value="Envoyer" />
<NavLink to={'/'}> <input type="submit" value="Ajouter des articles " /> </NavLink> </p>
</fieldset>
</form>
</center>
</div>
);
}
}
export default Test
it's an application that does the same job as uber eat..
the submit form allows you to save orders
I want to save each of the commands taken by the user
I also want to give each order a unique number
it's an application that does the same job as uber eat..
I need to update options so that later useCallback will process it, but when I click on the checkbox, nothing changes.
But if you comment out setOptions, then the checkbox changes
const [options, setOptions] = useState({
s22: {value: 'TRUE', s: 22},
s23: {value: 'TRUE', s: 23},
s24: {value: 'TRUE', s: 24}
})
const changeFilter = event => {
setOptions({ ...options, [event.target.name]: {
value: event.target.checked.toString().toUpperCase(),
s: event.target.value
}
})
}
<div id="filter">
<p>
<label>
<input name="s22" type="checkbox" value="22" onChange={changeFilter} />
<span>УК</span>
</label>
</p>
<p>
<label>
<input name="s23" type="checkbox" value="23" onChange={changeFilter} />
<span>ФК</span>
</label>
</p>
<p>
<label>
<input name="s24" type="checkbox" value="24" onChange={changeFilter} />
<span>ФТ</span>
</label>
</p>
</div>
Found similar questions but there was a problem with preventDefault
Full code
import React, {useCallback, useContext, useEffect, useState} from 'react'
import {useHttp} from '../hooks/http.hook'
import {AuthContext} from '../context/AuthContext'
import {Loader} from '../components/Loader'
export const TreePage = () => {
const [tree, setTree] = useState([])
const [options, setOptions] = useState({
s22: {value: 'TRUE', s: 22},
s23: {value: 'TRUE', s: 23},
s24: {value: 'TRUE', s: 24}
})
const {loading, request} = useHttp()
const {token} = useContext(AuthContext)
const fetchTree = useCallback(async () => {
try {
const fetched = await request('/api/tree', 'GET', options, {
Authorization: `Bearer ${token}`
})
setTree(fetched)
} catch (e) {}
}, [token, request, options])
useEffect(() => {
fetchTree()
}, [fetchTree])
useEffect(() => {
var zoom = 1;
var zoomStep = 0.1;
document.getElementById("zoomIn").addEventListener("click",function(){
zoom += zoomStep; document.getElementById("zoomtext").style.transform = "scale("+zoom+")";
});
document.getElementById("zoomOut").addEventListener("click",function(){
if(zoom > zoomStep){
zoom -= zoomStep;
document.getElementById("zoomtext").style.transform = "scale("+zoom+")";
}
});
})
const changeFilter = event => {
setOptions({ ...options, [event.target.name]: {
value: event.target.checked.toString().toUpperCase(),
s: event.target.value
}
})
}
if (loading) {
return <Loader/>
}
return (
<>
{!loading &&
<div className="row">
<div className="col s6 offset-s3">
<div id="filter">
<p>
<label>
<input name="s22" type="checkbox" value="22" onChange={changeFilter} />
<span>УК</span>
</label>
</p>
<p>
<label>
<input name="s23" type="checkbox" value="23" onChange={changeFilter} />
<span>ФК</span>
</label>
</p>
<p>
<label>
<input name="s24" type="checkbox" value="24" onChange={changeFilter} />
<span>ФТ</span>
</label>
</p>
</div>
<div dangerouslySetInnerHTML={{__html: tree}}></div>
</div>
</div>
}
</>
)
}
I'm using SendGrid to send emails in my serverless Next.js project, deployed in Vercel, which works perfectly in development mode. But I'm having problems in production.
The error returned is:
contact-us-4c7332c1e7bfe2127d39.js:1 POST https://mywebsite.vercel.app/api/send 400
Yes, I enabled "Allow Less Secured Apps" in Google account and verify a Sender Identity in SendGrid.
Anybody experienced this kind of problem? How can I fix this?
This is the contact-us.js page
import Head from 'next/head'
import React, { useState } from 'react'
export default () => {
const [status, setStatus] = useState({
submitted: false,
submitting: false,
info: { error: false, msg: null }
})
const [inputs, setInputs] = useState({
name: '',
phone: '',
email: '',
message: ''
})
function SubmitButton(){
if (inputs.name && inputs.email && inputs.message) {
return <button type="submit" className="btn-submit" disabled={status.submitting}> {!status.submitting ? !status.submitted ? 'Submit' : 'Submitted' : 'Submitting...'} </button>
} else {
return <button type="submit" className="btn-submit" disabled>Submit</button>
};
};
const handleResponse = (status, msg) => {
if (status === 200) {
setStatus({
submitted: true,
submitting: false,
info: { error: false, msg: msg }
})
setInputs({
name: '',
phone: '',
email: '',
message: ''
})
} else {
setStatus({
info: { error: true, msg: msg }
})
}
}
const handleOnChange = e => {
e.persist()
setInputs(prev => ({
...prev,
[e.target.id]: e.target.value
}))
setStatus({
submitted: false,
submitting: false,
info: { error: false, msg: null }
})
}
const handleOnSubmit = async e => {
e.preventDefault()
setStatus(prevStatus => ({ ...prevStatus, submitting: true }))
const res = await fetch('/api/send', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(inputs)
})
const text = await res.text()
handleResponse(res.status, text)
}
return (
<div className="contact">
<main>
<div>
<h2>Get in touch!</h2>
<h3>How can we help you?</h3>
</div>
<form onSubmit={handleOnSubmit}>
<div className="form-group">
<input
id="name"
type="text"
name="name"
onChange={handleOnChange}
required
value={inputs.name}
className={inputs.name ? "form-control active" : "form-control"}
/>
<label className="form-label" htmlFor="name">Name</label>
</div>
<div className="form-group">
<input
id="email"
type="text"
name="email"
onChange={handleOnChange}
required
value={inputs.email}
className={inputs.email ? "form-control active" : "form-control"}
/>
<label className="form-label" htmlFor="email">Email</label>
</div>
<div className="form-group">
<input
id="phone"
type="tel"
name="phone"
onChange={handleOnChange}
required
value={inputs.phone}
className={inputs.phone ? "form-control active" : "form-control"}
/>
<label className="form-label" htmlFor="phone">Phone</label>
</div>
<div className="form-group">
<textarea
id="message"
onChange={handleOnChange}
required
value={inputs.message}
className={inputs.message ? "form-control active" : "form-control"}
/>
<label className="form-label" htmlFor="message">Message</label>
</div>
<SubmitButton />
{status.info.error && (
<div className="message-feedback error">
<p>Error: {status.info.msg}</p>
</div>
)}
{!status.info.error && status.info.msg && (
<div className="message-feedback success">
<p>Thanks for messaging us!</p>
<p>We'll get back to you soon.</p>
</div>
)}
</form>
</main>
</div>
)
}
And the /api/send.js
const sgMail = require('#sendgrid/mail')
export default async function(req, res) {
sgMail.setApiKey(process.env.SENDGRID_API_KEY)
const { phone, email, message } = req.body
const msg = {
to: 'myemail#outlook.com', // Change to your recipient
from: 'mysenderemail#gmail.com', // Change to your verified sender
subject: `New Message From - ${email}`,
text: message,
html: `
<p>Phone: ${phone}</p>
<p>Sent from: ${email}</p>
<div>${message}</div>
`
}
try {
await sgMail.send(msg)
res.status(200).send('Message sent successfully.')
} catch (error) {
console.log('ERROR', error)
res.status(400).send('Message not sent.')
}
}
Thank you.
i can upload image with postman but in angular it doesn't work for me. solution please
error : cannot read originalname of undefined , in nodejs but with
postman its work !
//backend
var express = require("express")
var router = express.Router();
var userModel = require("../models/userModel")
const jwt= require("jsonwebtoken")
const bcrypt=require("bcrypt")
var app=express()
var io = require('socket.io-client')('http://localhost:3000/alll')
var socket = require("socket.io");
var fs=require("fs")
var multer=require("multer")
const upload = multer({dest: __dirname + '/upload/images'});
router.post('/uploads', upload.single('image'), function (req, res) {
var file = __dirname + '/upload' + req.file.originalname;
fs.readFile(req.file.path, function (err, data) {
fs.writeFile(file, data, function (err) {
if (err) {
console.error(err);
var response = {
message: 'Sorry, file couldn\'t be uploaded.',
filename: req.file.originalname
};
} else {
response = {
message: 'File uploaded successfully',
filename: req.file.originalname
};
res.json(response);
}
})
})
})
router.post("/add",function (req, res) {
user = new userModel({firstName: req.body.firstName,
lastName: req.body.lastName ,
email:req.body.email ,
password:req.body.password,
adresse:req.body.adresse,
verif:'1',role :'user',
annonces:req.body.annonces,
pdf: req.body.pdf
})
user.save(function(err) {
if (err) {
res.send({"state": "not ok", "msg": "err:" + err})
} else {
res.send({"state": " ok", "msg": "ajout"})
}
})
})
// model : pdf as String
//ts
import {ChangeDetectorRef, Component, OnInit, TemplateRef} from '#angular/core';
import {FormBuilder, FormGroup, Validators} from '#angular/forms';
import {Router} from '#angular/router';
import {UserService} from '../services/user.service';
import {ConnecterComponent} from '../connecter/connecter.component';
import {BsModalRef, BsModalService} from 'ngx-bootstrap/modal';
import { FileUploader } from 'ng2-file-upload';
#Component({
selector: 'app-singin',
templateUrl: './singin.component.html',
styleUrls: ['./singin.component.css']
})
export class SinginComponent implements OnInit {
registrationForm: FormGroup;
submit = false;
fileSelected: File
emailuser: String;
modalRef: BsModalRef;
selectedFiles: FileList;
currentFileUpload: File;
imgURL: any;
imgname;
errorValidImage = '';
URL ='http://localhost:3000/users/uploads';
constructor(private router: Router, private userService: UserService, private formbuilder: FormBuilder , private cd : ChangeDetectorRef, private modalService: BsModalService ) { }
ngOnInit() {
this.registrationForm = this.formbuilder.group({
email: [ '', [ Validators.required, Validators.email]],
password: ['', [ Validators.required, Validators.minLength(8)]],
firstName:['',[ Validators.required]],
lastName: ['', Validators.required],
adresse:['', Validators.required],
pdf:[''],
});
}
get f() {
return this.registrationForm.controls;
}
OnSubmit(){
this.submit = true;
if (this.registrationForm.invalid) {
return;
}
console.log(this.registrationForm.value)
localStorage.setItem('var', '1');
this.userService.updateimagee(this.currentFileUpload).subscribe(res=>{
this.imgname=JSON.parse(JSON.stringify(res['filename']));
this.userService.register(this.registrationForm.value.firstName,this.registrationForm.value.lastName,this.registrationForm.value.email,this.registrationForm.value.password,this.registrationForm.value.adresse,this.registrationForm.value.pdf=this.imgname).subscribe( res => {
console.log(res['status'])
});
this.userService.login(this.registrationForm.value.email,this.registrationForm.value.password).subscribe(res=>{
localStorage.setItem('var', '1')
localStorage.setItem('emailuser',JSON.parse(JSON.stringify(res['data'])).email)
this.emailuser=localStorage.getItem('emailuser')
console.log(res['status'])
console.log(JSON.parse(JSON.stringify(res['data'])).token);
// console.log(JSON.parse(JSON.stringify(res['data'])).id);
var iduser = parseInt(JSON.parse(JSON.stringify(res['data'])).id);
sessionStorage.setItem('id', JSON.parse(JSON.stringify(res['data'])).id);
this.router.navigate(['']);
})
})
}
selectFile(event) {
this.selectedFiles =event.target.files;
this.currentFileUpload = this.selectedFiles.item(0);
console.log(this.currentFileUpload);
const reader = new FileReader();
reader.onload = (event) => {
this.imgURL = reader.result;
};
console.log(this.imgURL);
console.log(reader);
} }
//html
<div class="container">
<form method="POST" class="appointment-form" id="appointment-form" [formGroup]="registrationForm" (ngSubmit)="OnSubmit()" enctype="multipart/form-data">
<h2>education appointment form</h2>
<div class="form-group-1">
<div [class]="form-control" >
<input type="text" class="form-control" formControlName="firstName" placeholder="First Name" [ngClass]="{'is-invalid':submit && f.firstName.errors} " />
<span class="focus-input100" data-placeholder=""></span>
<div *ngIf="submit && f.firstName.errors" class="invalid-feedback">
<div *ngIf="f.firstName.errors.required">firstName is required </div>
</div>
</div>
<div [class]="form-control" >
<input type="text" formControlName="lastName" placeholder="Last Name" class="form-control" [ngClass]="{'is-invalid':submit && f.lastName.errors}" />
<div *ngIf="submit && f.lastName.errors" class="invalid-feedback">
<div *ngIf="f.lastName.errors.required">LastName is required </div>
</div>
</div>
<div [class]="form-control" >
<input type="email" formControlName="email" placeholder="Email" class="form-control" [ngClass]="{'is-invalid':submit && f.email.errors}" />
<div *ngIf="submit && f.email.errors" class="invalid-feedback">
<div *ngIf="f.email.errors.required">Email is required </div>
</div>
</div>
<div [class]="form-control" >
<input type="password" formControlName="password" placeholder="Password" class="form-control" [ngClass]="{'is-invalid':submit && f.password.errors}" />
<div *ngIf="submit && f.password.errors" class="invalid-feedback">
<div *ngIf="f.password.errors.required">Password is required </div>
<div *ngIf="f.password.errors.minlength">Au moins 8 caracteres </div>
</div>
</div>
<div [class]="form-control" >
<input type="text" formControlName="adresse" placeholder="Adresse local" class="form-control" [ngClass]="{'is-invalid':submit && f.adresse.errors}" />
<div *ngIf="submit && f.adresse.errors" class="invalid-feedback">
<div *ngIf="f.adresse.errors.required">Adresse is required </div>
</div>
</div>
<div class="custom-file">
<input type="file" class="custom-file-input" id="customFile" (change)="selectFile($event)" formControlName="pdf" [ngClass]="{'is-invalid':submit && f.pdf.errors}" />
<label class="custom-file-label">Photo de profil</label>
</div>
<div class="form-submit">
<input type="submit" name="submit" id="submit" class="submit" value="Submit" />
</div>
</div>
</form>
</div>
</div>
but console say that there is error in back-end that :
TypeError: Cannot read property 'originalname' of undefined
at C:\Users\hazem\Desktop\pfe\router\user.js:114:47
It seems like you have not used the library ng2-file-upload Try something like this.
import { Component, OnInit } from '#angular/core';
import { FileUploader, FileSelectDirective } from 'ng2-file-upload/ng2-file-upload';
const UploadURL = 'http://localhost:3000/api/upload';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'Upload a File';
public uploader: FileUploader = new FileUploader({url: URL, itemAlias: 'image'});
ngOnInit() {
this.uploader.onAfterAddingFile = (file) => { file.withCredentials = false; };
this.uploader.onCompleteItem = (item: any, response: any, status: any, headers: any) => {
console.log('FileUpload:uploaded:', item, status, response);
alert('File uploaded successfully');
};
}
}
The line
public uploader: FileUploader = new FileUploader({url: URL, itemAlias: 'image'});
is important. make sure you use the same name('image') in you multer middleware,
like this
upload.single('image')
II am trying to do a post request to the database to post an object called questions using "react-dom": "^15.6.1". The data might be something as follows:
{description: 'What is E-commerce?', ismeeting: false, expID: '123A2'}
What i am trying to do is take the "description" , "ismeeting" and ,"expID" values from a form and a checkbox (checkbox for "ismeeting") in the front end and pass it to the backend. To get the description value for instance; i am using this.refs.description.value. However i am getting an error Using this.refs is deprecated in the onSubmit(e) function and Using string literals in ref attributes is deprecated react/no-string-refs in the render() function
Here is the OnSubmit code.
onSubmit(e) {
const newQues = {
description: this.refs.description.value,
ismeeting: this.refs.check_me.checked,
expID: this.refs.expID.value
};
this.addQues(newQues);
e.preventDefault();
}
and here is the render() code.
render() {
return (
<div>
<br/>
<h1> DO NOT HESISTATE TO ASK OUR EXPERTS </h1>
<form onSubmit={this.onSubmit.bind(this)}>
<div className="input-field">
<input type="text" name="description" ref="description"/>
<label htmlFor="description"> Description </label>
</div>
<div className="input-field">
<input type="text" name="expID" ref="expID"/>
<label htmlFor="name"> expID </label>
</div>
<div className="checkbox">
<label>
<input type="checkbox" name="ismeeting" ref="check_me" />Meeting
</label>
</div>
<input type ="submit" value="ASK" className="btn" />
</form>
</div>
);
}
finally this is the full code.
import React, { Component } from 'react';
import axios from 'axios';
import '../Styles.scss';
class Questions extends Component {
addQues(newQues) {
console.log(newQues);
axios.request({
method: 'Post',
url: 'http://localhost:3001/api/Questions',
data: newQues
}).then(response => {
}).catch(err => console.log(err));
}
constructor() {
super();
this.state = {
Questions: []
};
}
onSubmit(e) {
const newQues = {
description: this.refs.description.value,
ismeeting: this.refs.check_me.checked,
expID: this.refs.expID.value
};
this.addQues(newQues);
e.preventDefault();
}
render() {
return (
<div>
<br/>
<h1> DO NOT HESISTATE TO ASK OUR EXPERTS </h1>
<form onSubmit={this.onSubmit.bind(this)}>
<div className="input-field">
<input type="text" name="description" ref="description"/>
<label htmlFor="description"> Description </label>
</div>
<div className="input-field">
<input type="text" name="expID" ref="expID"/>
<label htmlFor="name"> expID </label>
</div>
<div className="checkbox">
<label>
<input type="checkbox" name="ismeeting" ref="check_me" />Meeting
</label>
</div>
<input type ="submit" value="ASK" className="btn" />
</form>
</div>
);
}
}
export default Questions;
String refs have been deprecated. So what you need to do is update your refs
<input type="text" name="expID" ref="expID"/>
should be updated to
setExpIdRef = (r) => this.expIdRef = r;
onSubmit = (e) => {
const newQues = {
expID: this.expIdRef.value
};
// Do what you need to with newQuest i.e call your database
}
render() {
...
<input type="text" name="expID" ref={this.setExpIdRef}/>
}
The best solution is to make your inputs controlled inputs. Where you keep track of the value in the state.
constructor() {
super();
this.state = {
expID: ''
};
}
onExpIdChange = (e) => {
this.setState({
expID: e.target.value
})
}
onSubmit = (e) => {
const newQues = {
expID: this.state.expID
};
// Do what you need with the newQues object
}
render() {
...
<input type="text" name="expID" onChange={this.onExpIdChange} />
}