can't upload images using react to backend using axios and nodejs - node.js

I try to upload a photo from React and save it in a public folder on the backend and then display the filename in the MySql database
After trying it through Postman, the photo has been successfully uploaded and appears and produces a json like this
{"image":"/img/14d714a9ed97fb92db657b9518e89a1e.png",
"id_produk":23,
"id_user":19,
"Nama_toko":"Nihongo Mantappu",
"Nama_Produk":"Butter",
"Deskripsi":"Mentega Blueband 50g",
"Price":5000,
"Jumlah_stock":7},
but when I tried it in React it only produced this
{"image":"/img/",
"id_produk":29,
"id_user":19,
"Nama_toko":"Nihongo Mantappu",
"Nama_Produk":"Beras Cinajur",
"Deskripsi":"Beras Cianjur 1kg",
"Price":500000,"Jumlah_stock":20}
so that when i check the database on the image it becomes empty
here the code for upload image
import React from 'react'
import jwt_decode from 'jwt-decode';
import 'bootstrap/dist/css/bootstrap.min.css';
import NavbarPenjual from '../../Component/NavbarPenjual';
import {addproduk} from '../../View/UserFunctions';
import { Form,Col, Button } from 'react-bootstrap';
class TambahProduk extends React.Component{
constructor(){
super()
this.state={
id_user:'',
Nama_toko:'',
Nama_produk: '',
Harga:'',
image: '',
Deskripsi: '',
Jumlah_produk: '',
error:{}
}
this.onChange=this.onChange.bind(this)
this.onSubmit=this.onSubmit.bind(this)
}
onChange(e){
this.setState({[e.target.name]:e.target.value})
}
componentDidMount(){
const token = localStorage.getItem('usertoken')
const decoded= token ? jwt_decode(token) : null;
this.setState({
id_user:decoded.id_user,
Nama_toko:decoded.Nama_toko
})
}
onSubmit(e){
e.preventDefault()
const newProduk={
id_user:this.state.id_user,
Nama_toko:this.state.Nama_toko,
Nama_Produk: this.state.Nama_Produk,
Price:this.state.Price,
image: this.state.image,
Deskripsi: this.state.Deskripsi,
Jumlah_stock: this.state.Jumlah_stock,
}
console.log(newProduk)
addproduk(newProduk).then(res =>{
//localStorage.setItem('usertoken',res.data.token);
this.props.history.push(`/DashboardPenjual`)
}).catch(err=>{
console.log(err)
alert("gagal")
})
}
render(){
return(
<div>
<NavbarPenjual/>
<Form className="container"style={{marginTop:28}} noValidate onSubmit={this.onSubmit}>
<h2>Tambah Produk</h2>
<Form.Row controlId="exampleForm.ControlInput1">
<Form.Label column lg={2}>
Nama Produk
</Form.Label>
<br/>
<Col>
<Form.Control
type="text"
placeholder="Masukan Nama Produk"
name="Nama_Produk"
value={this.state.Nama_Produk}
onChange={this.onChange}
/>
</Col>
</Form.Row>
<br/>
<Form.Row controlId="exampleForm.ControlInput1">
<Form.Label column lg={2}>
Harga Produk
</Form.Label>
<br/>
<Col>
<Form.Control type="text"
placeholder="Masukan Harga Produk"
name="Price"
value={this.state.Price}
onChange={this.onChange}
/>
</Col>
</Form.Row>
<br/>
<Form.Row controlId="exampleForm.ControlInput1">
<Form.Label column lg={2}>
Jumlah Produk
</Form.Label>
<br/>
<Col>
<Form.Control
type="text"
placeholder="Masukan Jumlah Produk"
name="Jumlah_stock"
value={this.state.Jumlah_stock}
onChange={this.onChange}
/>
</Col>
</Form.Row>
<br/>
<Form.Row controlId="exampleForm.ControlInput1">
<Col>
<Form.Group controlId="exampleForm.ControlTextarea1">
<Form.Label>Deskripsi Produk</Form.Label>
<br/>
<Form.Control
as="textarea"
rows="3"
name="Deskripsi"
value={this.state.Deskripsi}
onChange={this.onChange}
/>
</Form.Group>
</Col>
</Form.Row>
<br/>
<Form.Row controlId="exampleForm.ControlInput1">
<Form.Group>
<Form.File
id="exampleFormControlFile1"
label="Masukan Foto Produk"
type="image"
name="image"
value={this.state.image}
onChange={this.onChange}
/>
</Form.Group>
</Form.Row>
<br/>
<button
type="submit"
className="btn btn-lg btn-primary btn-block"
>Submit</button>
<Form.Row controlId="exampleForm.ControlInput1" style={{ visibility: "hidden" }}>
<Col>
<Form.Group controlId="exampleForm.ControlInput1">
<br/>
<Form.Control
as="text"
name="id_user"
value={this.state.id_user}
onChange={this.onChange}
/>
</Form.Group>
</Col>
</Form.Row>
<Form.Row controlId="exampleForm.ControlInput1" style={{ visibility: "hidden" }}>
<Col>
<Form.Group controlId="exampleForm.ControlTextarea1">
<br/>
<Form.Control disabled
as="area"
name="Nama_toko"
value={this.state.Nama_toko}
onChange={this.onChange}
/>
</Form.Group>
</Col>
</Form.Row>
</Form>
</div>
)
}
}
export default TambahProduk;
this is part of the axios userfuction for add product
export const addproduk = newProduk =>{
return axios
.post('product/addproduk',{
id_user:newProduk.id_user,
Nama_toko:newProduk.Nama_toko,
Nama_Produk:newProduk.Nama_Produk,
image: newProduk.image,
Deskripsi:newProduk.Deskripsi,
Price:newProduk.Price,
Jumlah_stock:newProduk.Jumlah_stock
})
.then(res=>{
console.log("produk di tambahkan")
return res
})
.catch(err=>{
console.log(err);
return err;
})
}
How do I get uploaded like when I use Postman?

Image is not an value, it's a file. So, in the onChange function you assigned the image.target.name as value
Try like this :
event.target.name === "image"? event.target.files[0] : event.target.value;

Related

Path validation error when pushing in react but works in postman/node directly

I am trying to push info from my sign up page . I can display it and even get an error 500 but i see a path validation even though i can directly post from postman to my db. Here is my signUp page . My model and route is written all the same so i dont understand
import React from "react";
import {
MDBBtn,
MDBContainer,
MDBRow,
MDBCol,
MDBCard,
MDBCardBody,
MDBCardImage,
MDBInput,
MDBIcon,
MDBCheckbox,
} from "mdb-react-ui-kit";
import Navbar from "./Navbar";
import Footer from "./Footer";
import {useState} from "react";
// const initFormData = Object({
// //declaration de l'objet initiale pour recevoir les credentials
// username: "",
// email: "",
// password: "",
// // passwordCheck: "",ls
// });
const SignUpForm = () => {
const [username, setUsername] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const collectData = async () => {
console.warn("warn" , username,email,password)
let result = await fetch("http://localhost:8000/api/auth/register",{
method: "post",
body: JSON.stringify({username,email,password}),
headers:{
'Content-type':'shop/JSON'
}
});
result = await result.json();
console.warn(result);
}
return (
<>
<Navbar />
<MDBContainer fluid>
<MDBCard className="text-black m-5" style={{borderRadius: "25px"}}>
<MDBCardBody>
<MDBRow>
<MDBCol
md="10"
lg="6"
className="order-2 order-lg-1 d-flex flex-column align-items-center"
>
<p className="text-center h1 fw-bold mb-5 mx-1 mx-md-4 mt-4">
Sign up
</p>
<div className="d-flex flex-row align-items-center mb-4 ">
<MDBIcon fas icon="user me-3" size="lg" />
<MDBInput
label="Votre Nom"
id="form1"
type="text"
className="w-100"
value={username}
onChange={(e) => setUsername("username", e.target.value)}
/>
</div>
<div className="d-flex flex-row align-items-center mb-4 ">
<MDBIcon fas icon="user me-3" size="lg" />
<MDBInput
label="Email"
id="email"
type="email"
className="w-100"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<div className="d-flex flex-row align-items-center mb-4">
<MDBIcon fas icon="lock me-3" size="lg" />
<MDBInput
label="Mot de passe"
id="form3"
type="password"
name="password"
value={password}
onChange={(e) => setPassword("password" , e.target.value)}
/>
</div>
<div className="mb-4">
<MDBCheckbox
name="flexCheck"
value=""
id="flexCheckDefault"
label="Subscribe to our newsletter"
/>
</div>
<MDBBtn className="mb-4" size="lg" onClick={collectData()}>
Register
</MDBBtn>
</MDBCol>
<MDBCol
md="10"
lg="6"
className="order-1 order-lg-2 d-flex align-items-center"
>
<MDBCardImage
src="https://mdbcdn.b-cdn.net/img/Photos/new-templates/bootstrap-registration/draw1.webp"
fluid
/>
</MDBCol>
</MDBRow>
</MDBCardBody>
</MDBCard>
</MDBContainer>
<Footer />
</>
);
};
export default SignUpForm;
i expected to be able to push but i get

Cannot access 'useState' before initialization in react.js

In react.js I am adding a form with some parameter.
import React , {useState} from "react";
AddUser component has some parameter in which I have to store data.
const AddUser = () => {
const [user, useState] = useState({
name: " ",
username: " ",
email: " ",
phone: " ",
website: " "
});
This code is used for initializing the parameter of useState.
const {name,username,email,phone,website} = user;
const onInputChange = e => {
console.log(e.target.value)
}
return (
<div className="container mt-5">
<div className="w-75 mx-auto shadow p-5">
<h2 className="text-center mb-4">Add User</h2>
This is the form where I submit some data of parameters.
<form>
<div class="form-group mb-4">
<input type="text" value={name} name="name" onChange={e => onInputChange(e)} class="form-control" aria-describedby="emailHelp" placeholder="Enter Name" />
</div>
<div class="form-group mb-4">
<input type="text" value={username} name="username" onChange={e => onInputChange(e)} class="form-control" placeholder="Enter Username" />
</div>
<div class="form-group mb-4">
<input type="email" value={email} name="email" onChange={e => onInputChange(e)} class="form-control" aria-describedby="emailHelp" placeholder="Enter email" />
</div>
<div class="form-group mb-4">
<input type="text" value={phone} name="phone" onChange={e => onInputChange(e)} class="form-control" placeholder="Enter Contact" />
</div>
<div class="form-group mb-4">
<input type="text" value={website} name="website" onChange={e => onInputChange(e)} class="form-control" placeholder="Enter Website" />
</div>
<button type="submit" class="btn btn-primary">Add User</button>
</form>
</div>
</div>
)
}
export default AddUser;
Error:
Uncaught ReferenceError: Cannot access 'useState' before initialization
at AddUser (AddUser.js:4:1)
at renderWithHooks (react-dom.development.js:16305:1)
at mountIndeterminateComponent (react-dom.development.js:20074:1)
at beginWork (react-dom.development.js:21587:1)
at beginWork$1 (react-dom.development.js:27426:1)
at performUnitOfWork (react-dom.development.js:26557:1)
at workLoopSync (react-dom.development.js:26466:1)
at renderRootSync (react-dom.development.js:26434:1)
at recoverFromConcurrentError (react-dom.development.js:25850:1)
at performConcurrentWorkOnRoot (react-dom.development.js:25750:1)
useState is a react hook, you cannot use its name to name a variable or function. Change your AddUser code shown on this page to this:
const AddUser = () => {
const [user, setUser] = useState({
name: " ",
username: " ",
email: " ",
phone: " ",
website: " "
});

Pass Parameter on Axios Update Request

I am trying to pass a MongoDB's ObjectId (_id) as a parameter when making an Axios update request. I have a multi-step form that I am working with; after the first step the users account is created and they are logged in. The update request is made on step 2 of the form, so at this point the user is already authenticated.
My update request is below:
const changeOnClick = e => {
const users = {
shareEmail,
filmmakerQuestion,
genres,
favoriteFilm,
imbd,
portfolio,
aboutYou
};
console.log(users)
axios
.put(`http://localhost:5000/users/update/:id`, users)
.then(res => console.log(res.body))
.catch(err => {
console.log(err);
});
NodeJs Route:
router.put('/update/:id', (req, res) => {
Users.findById(req.params.id)
.then(user => {
user.shareEmail = req.body.shareEmail;
user.filmmakerQuestion = req.body.filmmakerQuestion;
user.genres = req.body.genres;
user.favoriteFilms = req.body.favoriteFilms;
user.imbd = req.body.portfolio;
user.portfolio = req.body.portfolio;
user.aboutYou = req.body.aboutYou
user
.save()
.then(() => res.json("The User is UPDATED succesfully!"))
.catch(err => res.status(400).json(`Error: ${err}`));
})
.catch(err => res.status(400).json(`Error: ${err}`));
});
Form code (step 1):
import React, { useState, useContext } from 'react';
import Exit from '../cancel.svg';
import Modal from 'react-modal';
import { useForm } from "react-hook-form";
// import Register from './Components/register';
import axios from "axios";
// import { Redirect } from 'react-router-dom';
import { useHistory } from "react-router-dom";
import UserContext from "../context/UserContext";
Modal.setAppElement('#root');
const Profile = () => {
const [modalIsOpen, setModalIsOpen] = useState (true);
const { register, handleSubmit, errors } = useForm ();
const [shareEmail, setshareEmail] = useState();
const [filmmakerQuestion, setfilmmakerQuestion] = useState();
const [genres, setgenres] = useState();
const [favoriteFilm, setfavoriteFilm] = useState();
const [imbd, setimbd] = useState();
const [portfolio, setportfolio] = useState();
const [aboutYou, setaboutYou] = useState();
const onSubmit = (data) => console.log(data);
const { userData } = useContext(UserContext);
const history = useHistory();
const changeOnClick = e => {
const users = {
shareEmail,
filmmakerQuestion,
genres,
favoriteFilm,
imbd,
portfolio,
aboutYou
};
console.log(users)
axios
.put(`http://localhost:5000/users/${userData.user.id}`, users)
.then(res => console.log(res.body))
.catch(err => {
console.log(err);
});
history.push("/Landing/ProfilePic")
};
return(
<Modal isOpen={modalIsOpen} onRequestClose={() => setModalIsOpen(false)} className='createBorder'>
<form onSubmit={handleSubmit(changeOnClick)} encType="multipart/form-data" >
<div className='border-bottom'>
<img onClick= {() => setModalIsOpen(false)} src={Exit} className='exitButton-two' alt='X' />
<span className='complete-profile'>Complete your profile</span>
</div>
<div>
<p className='filmmakerQ'>Please mark if your email can be shared with filmmakers:</p>
<div className='shareblock'>
<input onChange={e => setshareEmail(e.target.value)} ref={register({required: false})} className='sharePosition' type="radio" htmlFor='shareEmail' value='yes' name="shareEmail"/>
<label htmlFor='shareEmail'>Yes, share my email with filmmakers</label>
</div>
<div className='shareblock'>
<input onChange={e => setshareEmail(e.target.value)} ref={register({required: false})} className='sharePosition' type="radio" htmlFor='noShare' value='no' name="shareEmail"/>
<label htmlFor='noShare'>No, do not share my email</label>
</div>
<p className='filmmakerQ'>Are you a filmmaker?</p>
<div className='shareblock'>
<input onChange={e => setfilmmakerQuestion(e.target.value)} ref={register({required: false})} className='sharePosition' type="radio" htmlFor='yesFilmmaker' value='yes' name="filmmakerQuestion" />
<label htmlFor='yesFilmmaker'>Yes, I am a filmmaker</label>
</div>
<div className='shareblock'>
<input onChange={e => setfilmmakerQuestion(e.target.value)} ref={register({required: false})} className='sharePosition' type="radio" htmlFor='noFilmmaker' value='no' name="filmmakerQuestion" />
<label htmlFor='noFilmmaker'>No, I am not a filmmaker</label>
</div>
<p className='filmmakerQ'>What genres of film do you like? Check all that apply:</p>
<div>
<div className='shareBox'>
<input onChange={e => setgenres(e.target.value)} ref={register({required: false})} value='horror' type="checkbox" htmlFor='horror' name="genres" />
<label htmlFor='horror' className='move'>Horror</label>
<input onChange={e => setgenres(e.target.value)} ref={register({required: false})} value='animation' type="checkbox" htmlFor='animation' name="genres" />
<label htmlFor='animation'>Animation</label>
</div>
<div className='shareBox'>
<input onChange={e => setgenres(e.target.value)} ref={register({required: false})} value='drama' type="checkbox" name="genres" />
<label htmlFor='drama' className='move'>Drama</label>
<input onChange={e => setgenres(e.target.value)} ref={register({required: false})} value='comedy' type="checkbox" htmlFor='comedy' name="genres" />
<label htmlFor='comedy' className='move'>Comedy</label>
</div>
</div>
<div>
<div className='shareBox'>
<input onChange={e => setgenres(e.target.value)} ref={register({required: false})} value='action' type="checkbox" htmlFor='action' name="genres" />
<label htmlFor='action' className='move'>Action</label>
<input onChange={e => setgenres(e.target.value)} ref={register({required: false})} value='documentary' type="checkbox" htmlFor='documentary' name="genres" />
<label htmlFor='documentary'>Documentary</label>
</div>
<div className='shareBox'>
<input onChange={e => setgenres(e.target.value)} ref={register({required: false})} value='scifi' type="checkbox" htmlFor='scifi' name="genres" />
<label htmlFor='scifi' className='movemore'>Sci-Fi</label>
<input onChange={e => setgenres(e.target.value)} ref={register({required: false})} value='expriemental' type="checkbox" name="genres" />
<label htmlFor='experimental'>Experimental</label>
</div>
</div>
<p className='filmmakerQ'>What are your favorite films?</p>
<input ref={register({required: false})} onChange={e => setfavoriteFilm(e.target.value)} className='inputsThree' name='favoriteFilm' autoComplete='off'></input>
<p className='minifieldsNew'>These will be shared to your profile.</p>
<p className='filmmakerQ'>Please share a link to your IMBD profile if available:</p>
<input ref={register({required: false})} onChange={e => setimbd(e.target.value)} className='inputsThree' name='imbd' autoComplete='off'></input>
<p className='minifieldsNew'>If you are a filmmaker, our community is very interested to learn more about what projects you have been a part of. This will be shared on your profile</p>
<p className='filmmakerQ'>If you have a link to a portfolio please share below:</p>
<input ref={register({required: false})} onChange={e => setportfolio(e.target.value)} className='inputsThree' name='portfolio' autoComplete='off'></input>
<p className='minifieldsNew'>This is your chance to show your work. This will be shared on your profile</p>
<p className='filmmakerQ'>Anything else you want to share about yourself?</p>
<input ref={register({required: false})} onChange={e => setaboutYou(e.target.value)} className='inputsThree' name='aboutYou' autoComplete='off'></input>
<p className='minifieldsNewNew'>Our community is very interested in learning more about you as a filmmaker</p>
</div>
<div>
<button type='submit' className='signupButton3'>Sign Up</button>
{/* <a onClick={handleSubmit(onSubmit)} type='submit' className='doneButtontwo'>
<span>Done</span>
</a> */}
<div>
<a href='/GetStarted' className='later'>I'll do this later</a>
</div>
</div>
</form>
</Modal>
)
}
export default Profile;
Form code (step 2):
<form onSubmit={handleSubmit(changeOnClick)} encType="multipart/form-data" >
<div className='border-bottom'>
<img onClick= {() => setModalIsOpen(false)} src={Exit} className='exitButton-two' alt='X' />
<span className='complete-profile'>Complete your profile</span>
</div>
<div>
<p className='filmmakerQ'>Please mark if your email can be shared with filmmakers:</p>
<div className='shareblock'>
<input onChange={e => setshareEmail(e.target.value)} ref={register({required: false})} className='sharePosition' type="radio" htmlFor='shareEmail' value='yes' name="shareEmail"/>
<label htmlFor='shareEmail'>Yes, share my email with filmmakers</label>
</div>
<div className='shareblock'>
<input onChange={e => setshareEmail(e.target.value)} ref={register({required: false})} className='sharePosition' type="radio" htmlFor='noShare' value='no' name="shareEmail"/>
<label htmlFor='noShare'>No, do not share my email</label>
</div>
<p className='filmmakerQ'>Are you a filmmaker?</p>
<div className='shareblock'>
<input onChange={e => setfilmmakerQuestion(e.target.value)} ref={register({required: false})} className='sharePosition' type="radio" htmlFor='yesFilmmaker' value='yes' name="filmmakerQuestion" />
<label htmlFor='yesFilmmaker'>Yes, I am a filmmaker</label>
</div>
<div className='shareblock'>
<input onChange={e => setfilmmakerQuestion(e.target.value)} ref={register({required: false})} className='sharePosition' type="radio" htmlFor='noFilmmaker' value='no' name="filmmakerQuestion" />
<label htmlFor='noFilmmaker'>No, I am not a filmmaker</label>
</div>
<p className='filmmakerQ'>What genres of film do you like? Check all that apply:</p>
<div>
<div className='shareBox'>
<input onChange={e => setgenres(e.target.value)} ref={register({required: false})} value='horror' type="checkbox" htmlFor='horror' name="genres" />
<label htmlFor='horror' className='move'>Horror</label>
<input onChange={e => setgenres(e.target.value)} ref={register({required: false})} value='animation' type="checkbox" htmlFor='animation' name="genres" />
<label htmlFor='animation'>Animation</label>
</div>
<div className='shareBox'>
<input onChange={e => setgenres(e.target.value)} ref={register({required: false})} value='drama' type="checkbox" name="genres" />
<label htmlFor='drama' className='move'>Drama</label>
<input onChange={e => setgenres(e.target.value)} ref={register({required: false})} value='comedy' type="checkbox" htmlFor='comedy' name="genres" />
<label htmlFor='comedy' className='move'>Comedy</label>
</div>
</div>
<div>
<div className='shareBox'>
<input onChange={e => setgenres(e.target.value)} ref={register({required: false})} value='action' type="checkbox" htmlFor='action' name="genres" />
<label htmlFor='action' className='move'>Action</label>
<input onChange={e => setgenres(e.target.value)} ref={register({required: false})} value='documentary' type="checkbox" htmlFor='documentary' name="genres" />
<label htmlFor='documentary'>Documentary</label>
</div>
<div className='shareBox'>
<input onChange={e => setgenres(e.target.value)} ref={register({required: false})} value='scifi' type="checkbox" htmlFor='scifi' name="genres" />
<label htmlFor='scifi' className='movemore'>Sci-Fi</label>
<input onChange={e => setgenres(e.target.value)} ref={register({required: false})} value='expriemental' type="checkbox" name="genres" />
<label htmlFor='experimental'>Experimental</label>
</div>
</div>
<p className='filmmakerQ'>What are your favorite films?</p>
<input ref={register({required: false})} onChange={e => setfavoriteFilm(e.target.value)} className='inputsThree' name='favoriteFilm' autoComplete='off'></input>
<p className='minifieldsNew'>These will be shared to your profile.</p>
<p className='filmmakerQ'>Please share a link to your IMBD profile if available:</p>
<input ref={register({required: false})} onChange={e => setimbd(e.target.value)} className='inputsThree' name='imbd' autoComplete='off'></input>
<p className='minifieldsNew'>If you are a filmmaker, our community is very interested to learn more about what projects you have been a part of. This will be shared on your profile</p>
<p className='filmmakerQ'>If you have a link to a portfolio please share below:</p>
<input ref={register({required: false})} onChange={e => setportfolio(e.target.value)} className='inputsThree' name='portfolio' autoComplete='off'></input>
<p className='minifieldsNew'>This is your chance to show your work. This will be shared on your profile</p>
<p className='filmmakerQ'>Anything else you want to share about yourself?</p>
<input ref={register({required: false})} onChange={e => setaboutYou(e.target.value)} className='inputsThree' name='aboutYou' autoComplete='off'></input>
<p className='minifieldsNewNew'>Our community is very interested in learning more about you as a filmmaker</p>
</div>
<div>
<button type='submit' className='signupButton3'>Sign Up</button>
{/* <a onClick={handleSubmit(onSubmit)} type='submit' className='doneButtontwo'>
<span>Done</span>
</a> */}
<div>
<a href='/GetStarted' className='later'>I'll do this later</a>
</div>
</div>
</form>
Use insomnia I see that the update endpoints work; additionally I see that if I manually take a userId and use it instead of the ":id" in the axios request, then the PUT request will update successfully.
If I send the form data right now on my local environment the network response is:
"Error: CastError: Cast to ObjectId failed for value \":id\" at path \"_id\" for model \"Users\""
I appreciate the help!

How to integrate 2checkout with reactjs and nodejs?

I am trying to integrate 2checkout API in my reactjs &nodejs project.I reffered the documents which 2co provided.I created an account and in that webhooks&API i have "Merchant Code" and "Secret Key" but there is no "Publishable key" and "Private Key" Why?
what i have is:
render = () => {
return(
<form id="myCCForm" onSubmit={this.Submit}>
<input
id="token"
name="token"
type="hidden"
value=""
></input>
<div>
<label>
<span>Card Number</span>
</label>
<input
id="ccNo"
type="text"
size="20"
value=""
autocomplete="off"
required
/>
</div>
<div>
<label>
<span>Expiration Date (MM/YYYY)</span>
</label>
<input
type="text"
size="2"
id="expMonth"
required
></input>
<span> / </span>
<input
type="text"
size="2"
id="expYear"
required
></input>
</div>
<div>
<label>
<span>CVC</span>
</label>
<input
id="cvv"
size="4"
type="text"
value=""
autocomplete="off"
required
></input>
</div>
<input type="submit" value="Submit Payment"></input>
</form>
)}
submit=()=>{
let args = {
sellerId: "",//gave merchant code here
publishableKey: "",//as there is no publishable key what will give here?
ccNo: "",
cvv: "",
expMonth: "",
expYear: ""
};
window.TCO.loadPubKey("sandbox", () => {
window.TCO.requestToken(args).then(data => {
console.log("data");
});
});
How can i resolve this problem?

axios duplicates post requests

I am currently finishing up with a MERN system and noticed this very weird bug , when i click submit in the react page the user is saved to Mongo db , a little bit later another user is saved with the same data.
Here is my code (React frontend)
import React from "react";
import withStyles from "#material-ui/core/styles/withStyles";
import InputLabel from "#material-ui/core/InputLabel";
// core components
import GridItem from "components/Grid/GridItem.jsx";
import GridContainer from "components/Grid/GridContainer.jsx";
import CustomInput from "components/CustomInput/CustomInput.jsx";
import Button from "components/CustomButtons/Button.jsx";
import Card from "components/Card/Card.jsx";
import CardHeader from "components/Card/CardHeader.jsx";
import CardAvatar from "components/Card/CardAvatar.jsx";
import CardBody from "components/Card/CardBody.jsx";
import CardFooter from "components/Card/CardFooter.jsx";
import axios from 'axios';
import avatar from "assets/img/faces/marc.jpg";
import Styles from './Styles'
import { Form, Field } from 'react-final-form'
const styles = {
cardCategoryWhite: {
color: "rgba(255,255,255,.62)",
margin: "0",
fontSize: "14px",
marginTop: "0",
marginBottom: "0"
},
cardTitleWhite: {
color: "#FFFFFF",
marginTop: "0px",
minHeight: "auto",
fontWeight: "300",
fontFamily: "'Roboto', 'Helvetica', 'Arial', sans-serif",
marginBottom: "3px",
textDecoration: "none"
}
};
class UserProfile extends React.Component {
onChange = (e) => {
/*
Because we named the inputs to match their
corresponding values in state, it's
super easy to update the state
*/
this.setState({ [e.target.name]: e.target.value });
console.log('data', this.state.name)
}
onSubmit = async (values , e) => {
alert('User Created ')
let data = values;
axios.post('/api/users/newuser', {data})
.then(result => console.log(result))
.catch(err => console.log(err))
}
state = {
id: '',
name: "",
address:"",
phonenumber: "",
isp: "",
account: "",
accounttype: "",
paid: '',
staticip:'',
staticipdate: Date,
bill: '',
balance: '',
username: '',
pass: '',
apip: ''
render(){
return <div>
<h1>Create New User</h1>
<h3>Unlimitik POS system V1.0</h3>
<Form
onSubmit={this.onSubmit}
initialValues={{ }}
render={({ handleSubmit, form, submitting, pristine, values }) => (
<form onSubmit={handleSubmit}>
<div>
<label>Full Name</label>
<Field
name="name"
component="input"
type="text"
placeholder="Full Name"
/>
</div>
<div>
<label>Address</label>
<Field
name="address"
component="input"
type="text"
placeholder="address"
/>
</div>
<div>
<label>Phone Number</label>
<Field
name="phonenumber"
component="input"
type="text"
placeholder="phonenumber"
/>
</div>
<div>
<label>ISP</label>
<Field
name="isp"
component="input"
type="text"
placeholder="isp"
/>
</div>
<div>
<label>Account</label>
<Field
name="account"
component="input"
type="text"
placeholder="account"
/>
</div>
<div>
<label>Account Type</label>
<Field
name="accounttype"
component="input"
type="text"
placeholder="accounttype"
/>
</div>
<div>
<label>Paid</label>
<Field
name="paid"
component="input"
type="text"
placeholder="paid"
/>
</div>
<div>
<label>Static IP</label>
<Field
name="staticip"
component="input"
type="text"
placeholder="staticip"
/>
</div>
<div>
<label>Static IP Date</label>
<Field
name="staticipdate"
component="input"
type="date"
placeholder="staticipdate"
/>
</div>
<div>
<label>Bill</label>
<Field
name="bill"
component="input"
type="text"
placeholder="bill"
/>
</div>
<div>
<label>Balance</label>
<Field
name="balance"
component="input"
type="text"
placeholder="balance"
/>
</div>
<div>
<label>username</label>
<Field
name="username"
component="input"
type="text"
placeholder="username"
/>
</div>
<div>
<label>pass</label>
<Field
name="pass"
component="input"
type="text"
placeholder="pass"
/>
</div>
<div>
<label>AP / IP</label>
<Field
name="apip"
component="input"
type="text"
placeholder="AP / IP"
/>
</div>
<div>
<label>Notes</label>
<Field name="notes" component="textarea" placeholder="Notes" />
</div>
<div className="buttons">
<button type="submit" disabled={submitting || pristine} >
Submit
</button>
<button
type="button"
onClick={form.reset}
>
Reset
</button>
</div>
<pre>{JSON.stringify(values, 0, 2)}</pre>
</form>
)}
/>
export default UserProfile;
What is happening is the request is saved in mongodb after 2 or 3 seconds ( no exact timing ) another request is send and a document is saved 2 times.
here is the route express.js
router.post('/newuser', async (req, res) => {
var x = Math.floor(Math.random() * Date.now() * 0.000000002);
const data = new User ({
id: x,
name: req.body.data.name,
address: req.body.data.address,
phonenumber: req.body.data.phonenumber,
isp: req.body.data.isp,
account: req.body.data.account,
accounttype: req.body.data.accounttype,
paid: req.body.data.paid,
staticip: req.body.data.staticip,
staticipdate: req.body.data.staticipdate,
bill: req.body.data.bill,
balance: req.body.data.balance,
username: req.body.data.username,
pass: req.body.data.pass,
apip: req.body.data.apip
} )
data.save()
.then(r => console.log(r))
.catch(err => console.log(err))
})
the log after (the ids are different since it is generated on backend not by form)
You seem to have 2 onSubmit handlers.
I would suggest removing one of them:
<Form
// onSubmit={this.onSubmit} <--- remove this line
initialValues={{ }}
render={({ handleSubmit, form, submitting, pristine, values }) => (
<form onSubmit={handleSubmit}>

Resources