Axios POST Request Gives 400 (Bad Request) Error on React - javascript

When I use the postman backend it works fine. But when using React and trying to add data to the database gives a 400 error.
When I use the console.log(newpost) it gives a new post object on the console. But I can't send the data to the database. How to fix this?
postman image
My React Code:
import React, {useState} from "react";
import axios from "axios";
export default function AddPost(){
const [topic,setTopic] = useState("")
const [dec,setDec] = useState("")
const [cate,setCate] = useState("")
function sendData(e){
e.preventDefault();
const newpost = {
topic,
dec,
cate
}
axios.post("http://localhost:8000/post/save",newpost)
.then(()=>{
alert("post added")
setTopic ("")
setDec ("")
setCate("")
}).catch((err)=>{
alert(`Not inserted ${err}`)
})
}
return(
<div className="container">
<form onSubmit={sendData} >
<div className="mb-3">
<label htmlFor="name" className="form-label">topic</label>
<input type="test" className="form-control" id="name" aria-describedby="emailHelp" onChange={(e)=>{
setTopic(e.target.value)
}} />
</div>
<div className="mb-3">
<label htmlFor="Age" className="form-label">description</label>
<input type="test" className="form-control" id="Age" onChange={(e)=>{
setDec(e.target.value)
}}/>
</div>
<div className="mb-3">
<label htmlFor="Gender" className="form-label">postCategory</label>
<input type="test" className="form-control" id="Gender" onChange={(e)=>{
setCate(e.target.value)
}}/>
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
<div/>
</div>
)
}

As per your postman's request, the request body is not correctly being passed from react code.The expected key name doesn't match. You need to change newpost variable as follows:
const newpost = {
topic,
description: dec,
postCategory: cate
}

Try adding named keys.
For example:
const newpost = {
topic: 'test',
dec: 'test',
cate: 'test'
}

Related

How do I make a POST request using axios in react?

I am having issues with the axios post request. When I click on the Button, nothing happens. What is supposed to happen is that the data that I enter into the input fields is submitted to the API. However, no redirect or anything happens when I click the Button. I am not sure whether the onClick function in the Button is never being triggered or whether the issue lies with the call of axios and then the useNavigate function. I have tried several different ways of using these function but none worked. It might be a syntactic issue as I am a beginner with react. Any help would be appreciated!
Full Code:
import axios from 'axios';
import React, { useState } from 'react';
import { Container, Button } from 'react-bootstrap';
import { useNavigate } from 'react-router-dom';
const AddContact = () => {
const [first_name, setFirstName] = useState("")
const [last_name, setLastName] = useState("")
const [mobile_number, setMobileNumber] = useState("")
const [home_number, setHomeNumber] = useState("")
const [work_number, setWorkNumber] = useState("")
const [email_address, setEmailAddress] = useState("")
const history = useNavigate();
const AddContactInfo = async () => {
let formField = new FormData();
formField.append('first_name', first_name)
formField.append('last_name', last_name)
formField.append('mobile_number', mobile_number)
formField.append('home_number', home_number)
formField.append('work_number', work_number)
formField.append('email_address', email_address)
await axios.post('http://localhost:8000/api/', {
data: formField
}).then(function (response) {
console.log(response.data);
history('/', { replace: true });
})
}
return (
<div>
<h1>Add contact</h1>
<Container>
<div className="form-group">
<input type="text"
className="form-control form-control-lg"
placeholder="Enter Your First Name"
first_name="first_name"
value={first_name}
onChange={(e) => setFirstName(e.target.value)} />
</div>
<div className="form-group">
<input type="text"
className="form-control form-control-lg"
placeholder="Enter Your Last Name"
last_name="last_name"
value={last_name}
onChange={(e) => setLastName(e.target.value)} />
</div>
<div className="form-group">
<input type="text"
className="form-control form-control-lg"
placeholder="Enter Your Mobile Number"
mobile_number="mobile_number"
value={mobile_number}
onChange={(e) => setMobileNumber(e.target.value)} /></div>
<div className="form-group">
<input type="text"
className="form-control form-control-lg"
placeholder="Enter Your Home Number"
home_number="home_number"
value={home_number}
onChange={(e) => setHomeNumber(e.target.value)} /></div>
<div className="form-group">
<input type="text"
className="form-control form-control-lg"
placeholder="Enter Your Work Number"
work_number="work_number"
value={work_number}
onChange={(e) => setWorkNumber(e.target.value)} /></div>
<div className="form-group">
<input type="text"
className="form-control form-control-lg"
placeholder="Enter Your Email Address"
email_address="email_address"
value={email_address}
onChange={(e) => setEmailAddress(e.target.value)} /></div>
<Button onClick={() => { AddContactInfo(); }}>
Add Contact
</Button>
</Container>
</div >
);
};
export default AddContact;
First rename AddContactInfo to addContactInfo and then:
<Button onClick={addContactInfo}>
Add Contact
</Button>
You should correct the method addContactInfo as below:
const AddContactInfo = () => {
let formField = new FormData();
formField.append('first_name', first_name)
formField.append('last_name', last_name)
formField.append('mobile_number', mobile_number)
formField.append('home_number', home_number)
formField.append('work_number', work_number)
formField.append('email_address', email_address)
axios.post('http://localhost:8000/api/', {
data: formField
}).then(function (response) {
console.log(response.data);
history('/', { replace: true });
})
}
Try This:
<Button onClick={AddContactInfo}>
Add Contact
</Button>
import axios from 'axios';
const url = 'http://localhost:8000/api/';
axios.post(url , formField)
.then(response => {
console.log(response.data);
history('/', { replace: true });
})
.catch(({response}) => {
console.log(response);
});
Try calling the function this way :)
<Button onClick={AddContactInfo}>
Add Contact
</Button>

React JS fetch function not sending any HTTP request

This very same React APP was working till yesterday and suddenly today it stopped working completely. The fetch is not working at all, it not sending the HTTP request at all as observed the Network tab of Firefox. What is wrong with this? It was the same code that perfectly worked yesterday and suddenly today it stops to work.
As you can see that there is absolutely no response from the server. Why there is no response code against the POST request, as seen in the first line?
React Code:
import React, { useState } from "react";
import { useHistory } from "react-router-dom";
export default function Login(props) {
const [email_id, setEmailId] = useState({ email_id: "" });
const [password, setPassword] = useState("");
const history = useHistory();
const submit = () => {
let finalOrder = JSON.stringify(email_id);
fetch("http://localhost:8080/Project/customer/login", {
method: "POST",
headers: { "Content-type": "application/json" },
body: finalOrder,
}).then((res) => {
if (res.ok) {
history.push("/AllProducts");
}
});
};
// sessionStorage.setItem("customer_id", JSON.stringify(result));
// alert(sessionStorage.getItem("customer_id"));
// history.push("/AllProducts");
const handleEmailChange = (e) => {
setEmailId({ email_id: e.target.value });
};
const handlePasswordChange = (e) => {
setPassword(e.target.value);
};
return (
<form>
<h3>Sign In</h3>
<div className="form-group d-flex w-25 p-3 position-relative">
<label>Email address : </label>
<input
type="email"
className="form-control"
placeholder="Enter email"
value={email_id.email_id}
onChange={handleEmailChange}
/>
</div>
<div className="form-group d-flex w-25 p-3">
<label>Password : </label>
<input
type="password"
className="form-control"
placeholder="Enter password"
value={password}
onChange={handlePasswordChange}
/>
</div>
<div className="form-group d-flex w-25 p-3">
<div className="custom-control custom-checkbox">
<input
type="checkbox"
className="custom-control-input"
id="customCheck1"
/>
<label className="custom-control-label" htmlFor="customCheck1">
Remember me
</label>
</div>
</div>
<button
onClick={submit}
className="btn btn-primary btn-block d-flex w-25 p-3"
>
Submit
</button>
</form>
);
}
What is this weird behavior? Can anyone help? #CrossOrigin("http://localhost:3000/") added in the JAVA controller.Thanks in advance.
PS: Getting perfect response in ARC.
Now it is giving the following error:
"Error in the console : Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource." got resolved automatically by adding type="button" to the button. Sounds weird but true.

Error(Cannot post on rendering a page) in Reactjs and node JS

I am building a registration page for my project and encountered an error Cannot POST / on rendering the web page .Earlier i also have made a login page which is working correctly by using almost same syntax. Here are my files.
1)Registration.js
import React,{Component} from 'react';
import Axios from 'axios';
class Registration extends Component{
constructor(props)
{
super(props);
this.state={
name:"",
gender:"",
city:"",
state:"",
email:"",
password:""
};
}
render(){
return(
<div class="main">
<h1>Sign up</h1>
<div className="container">
<div className="sign-up-content">
<form method="POST" class="signup-form" onSubmit={this.onSubmit}>
<h2 className="form-title">Register yourself below:-</h2>
<div className="form-textbox">
<label for="name">Full name</label>
<input type="text" name="name" id="name" value={this.state.name} onChange={this.onChangeName}/>
</div>
<div className="form-textbox">
<label for="Gender">Gender</label>
<input type="text" name="gender" id="gender" value={this.state.gender} onChange={this.onChangeGender}/>
</div>
<div className="form-textbox">
<label for="City">City</label>
<input type="text" name="city" id="city" value={this.state.city} onChange={this.onChangeCity}/>
</div>
<div className="form-textbox">
<label for="State">State</label>
<input type="text" name="State" id="State" value={this.state.state} onChange={this.onChangeSate}/>
</div>
<div className="form-textbox">
<label for="email">Email</label>
<input type="email" name="email" id="email" value={this.state.email} onChange={this.onChangeEmail}/>
</div>
<div className="form-textbox">
<label for="pass">Password</label>
<input type="password" name="pass" id="pass" value={this.state.password} onChange={this.onChangePassword}/>
</div>
{/* <div className="form-group">
<input type="checkbox" name="agree-term" id="agree-term" class="agree-term" />
<label for="agree-term" class="label-agree-term"><span><span></span></span>I agree all statements in Terms of service</label>
</div> */}
<div className="form-textbox">
<input type="submit" name="submit" id="submit" class="submit" value="Create account" />
</div>
</form>
<p className="loginhere">
Already have an account ? Log in
</p>
</div>
</div>
</div>
);
};
onChangeName=(e)=>{
this.setState({
name:e.target.value
});
};
onChangeGender=(e)=>{
this.setState({
gender:e.target.value
});
};
onChangeCity=(e)=>{
this.setState({
city: e.target.value
});
};
onChangeSate=(e)=>{
this.setState({
state:e.target.value
});
};
onChangeEmail=(e)=>{
this.setState({
email:e.target.value
});
};
onChangePassword=(e)=>{
this.setState({
password:e.target.value
});
};
onSubmit=(e)=>{
console.log("inside on submit");
const vals={...this.state};
Axios.post("http://localhost:4200/register",vals).then(res=>console.log(res.data));
};
}
export default Registration;
2)App.js
import React from 'react';
import Login from './Login';
import Registration from './Registration';
const App=()=>(
<Registration />
);
export default App;
3)index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />,document.getElementById('root'));
4)Node js server (server.js)
const express=require('express');
const bodyParser=require('body-parser');
const mysql=require('mysql');
const cors=require('cors');
const app=express();
app.use(cors());
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
const con=mysql.createConnection({
host:'localhost',
user:'root',
password:'root',
database:'reactProject'
});
// app.post('/login',(request,resposne)=>{
// const email=request.body.email;
// const password=request.body.password;
// console.log(email+" "+password)
// const sql='select * from login where email = "'+email+'" and password="'+password+'" ';
// con.query(sql,(err,result)=>{
// if(result.length)
// {
// console.log(result);
// console.log("signed in");
// }
// else{
// console.log(result);
// console.log("Not signed");
// }
// });
// });
app.post('/register',(request,resposne)=>{
const name=request.body.name;
const gender=request.body.gender;
const city=request.body.city;
const state=request.body.state;
const email=request.body.email;
const password=request.body.password;
console.log(name+" "+gender);
const sql=`insert into register(name,gender,city,state,email,password) values('${name}','${gender}','${city}','${state}','${email}','${password}')`;
con.query(sql,(result,error)=>{
console.log(result);
});
});
app.listen(4200,()=>{
console.log("Server at 4200");
});
The above files are server.js,App.js,index.js,Registration it might be that whenever i click on submit it doesnot go inside onSubmit function .
In React, when you create a custom function to handle form submission, you need to call event.preventDefault(). The problem you are getting is due to the fact that your HTML is trying to send a post request when you submit the form, which you haven't set it up to do.
Here is a similar question where you can find more detailed information: React - Preventing Form Submission.
So, a way to fix this would be to change your onSubmit function to something like this:
onSubmit=(e)=>{
console.log("inside on submit");
e.preventDefault();
const vals={...this.state};
Axios.post("http://localhost:4200/register",vals).then(res=>console.log(res.data));
};

React and Axios dont connect to backend

My code is not working, i am using node and React, the axios is trying to connect with the backend, but it fail.
When i try the connect in console:
image of firefox console
my code is: frontend/pages/login/index.js
import { FiLogIn } from 'react-icons/fi'
import {Link } from 'react-router-dom'
import api from '../../services/api'
import './styles.css'
export default function Login() {
const [name, setName] = useState('')
const [password, setPassword] = useState('')
async function handleLogin(e) {
e.preventDefault()
let data = ({
name,
password}
)
try {
let response = await api.post('session', data)
} catch(err){
console.log(err)
}
}
return (
<div className="login-conteiner">
<header>
<nav>
<div className="navlinks">
<Link to="/"><div className="li">Vega</div></Link>
<Link to="about.html"><div className="li">Sobre</div></Link>
</div>
</nav>
</header>
<main className="login">
<div className="heading">
<span className="blackblock"><h1>Vega Leads</h1></span>
<h2>Visualize todos os Leads <br /> da sua Instiuição <br /> e torne em alunos.</h2><br />
</div>
<div>
<form className="loginForm" id="form" onSubmit={handleLogin}>
<div className="loginItem"><label htmlFor="login">Login </label><input className="formInput" type="text" name="login" id="login"
value={name}
onChange={e => setName(e.target.value)} /></div><br />
<div className="loginItem"><label htmlFor="senha">Senha </label><input className="formInput" type="password" name="password" id="password"
value={password}
onChange={ e => setPassword(e.target.value) } /></div><br />
<button type="submit" className="startButton" id="postForm">Enviar <FiLogIn size={25} color="#11548f" /></button>
</form>
</div>
</main>
</div>
)}
Axios api: frontend/services/api.js
const api = axios.create({
baseURL: 'http://localhost:3333',
})
export default api
If you need more files to resolve my problem, ask me.
Thanks
i resolved the problem.
the problem is in the index of my backend (backend/src/index.js)
i forget the CORS module.
it is my code:
const routes = require('./routes')
const cors = require('cors')
const app = express()
app.use(cors())
app.use(express.json())
app.use(routes)
app.listen(3333)

TypeError: Cannot read property 'name' of undefined error in a controlled-component

I'm trying to get a date as user input through a controlled component but always running into this error "TypeError: Cannot read property 'name' of undefined". This is the piece of code that's causing the error. I'm using the react-datepicker module to get the Date input as when I try to use the HTML input type="date" i'm unable to disable previousdates.
import React, {Fragment,useState,useEffect} from 'react';
import {Link,withRouter} from 'react-router-dom';
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import {addTask} from '../../actions/task';
import { addDays } from 'date-fns';
const TaskForm = ({addTask}) => {
const [formData,setFormData] = useState({
description:'',
due_at:'',
toBeReminded:''
})
const onSubmit = e => {
e.preventDefault();
addTask(formData);
}
const onChange = e=>setFormData({...formData, [e.target.name]:e.target.value})
const {description,due_at} = formData;
return (
<Fragment>
<h1 className="large text-primary">
New Task
</h1>
<form className="form my-1" onSubmit={e=>onSubmit(e)}>
<div className="form-group">
<label htmlFor="descr">Description:</label><br/>
<input type="text" id="descr" placeholder="Task Description" name="description" value={description} onChange={e=> onChange(e)}/>
</div>
<div className="form-group">
<label htmlFor="due_date">Due Date for Task:</label><br></br>
<DatePicker id="due_date" minDate={addDays(new Date(), 1)} id="due_date" name="due_at" value={due_at} onChange={e=> onChange(e)} />
</div>
<div className="form-group">
<label htmlFor="reminder">Set Reminder:</label><br></br>
<input type="radio" id="yes" name="toBeReminded" value="true" onClick={e=> onChange(e)}/>
<label htmlFor="yes">Yes</label><br/>
<input type="radio" id="no" name="toBeReminded" value="false" onClick={e=> onChange(e)}/>
<label htmlFor="no">No</label><br></br>
</div>
<input type="submit" className="btn btn-dark my-1" value="Submit" />
<Link className="btn btn-light my-1" to="/tasks">Go Back</Link>
</form>
</Fragment>
)
}
TaskForm.propTypes = {
addTask:PropTypes.func.isRequired
}
export default connect(null,{addTask})(TaskForm);
Looking at the docs for react-datepicker, it doesn't look like its onChange receives an event, but the date.
You should use a separate handler for the date change handler since they expect different signatures.
const onChange = e => setFormData({...formData, [e.target.name]:e.target.value})
const onDateChange = date => setFormData({...formData, due_at: date})
There's a lot of other solutions that would work if you really want to stick to one change handler, but I recommend just creating two like above.
But.. you could do something like this (I don't really recommend this):
const onChange = e => {
if (typeof e === 'object') {
setFormData({...formData, [e.target.name]:e.target.value})
} else {
setFormData({...formData, due_at: e})
}
}
Or since you're declaring new inline functions already (its unnecessary by the way, just do onChange={onChange} unless you use the following approach) you could do this:
const onChange = (name, value) => setFormData({...formData, [e.target.name]:e.target.value})
// Regular inputs
onChange={e => onChange('input name', e.target.value)}
// Date input
onChange={date => onChange('input name', date)}
The bottom line is: you have to pay attention to what onChange is expected to receive. It will differ depending on the input type or the library implementation.

Categories