400 bad request while submitting form - node.js

i am getting an error like 400 bad request while submitting form don't know whats going on wrong please help to solve my error
This img will help you to catch error
https://ibb.co/X8NKGzd and https://ibb.co/Y8fXsBj
addMovie.js
This is my frontend addmovie logic
import React,{useState} from 'react';
import Navbar from '../pages/Navbar';
import Footer from '../pages/Footer';
import {Link} from 'react-router-dom';
import {isAuthenticated} from '../Auth/index';
import {addMovie} from '../Admin/adminapicall';
const AddMovie = () => {
const {user,token} = isAuthenticated();
const [values,setValues] = useState({
movie_name:'',
actor:'',
country_of_origin:'',
duration:'',
director:'',
photo:'',
loading:false,
error:'',
addedMovie:'',
getRedirect:false,
// formData:''
})
const {movie_name,actor,country_of_origin,duration,director,photo,loading,error,addedMovie,getRedirect} = values;
const handleChange = name => event => {
const value = name === "photo" ? event.target.files[0] : event.target.value
// formData.set(name,value);
setValues({...values,[name]:value})
};
const onSubmit = (e) => {
e.preventDefault();
setValues({...values,error:'',loading:true})
addMovie(user._id,token,JSON.stringify(values)).then(data =>{
if(data.error){
setValues({...values,error:data.error})
}else{
setValues({
...values,
movie_name:'',
actor:'',
country_of_origin:'',
duration:'',
director:'',
photo:'',
loading:false,
addedMovie: data.movie_name
})
}
})
}
const successMessage = () => (
<div className='alert alert-success mt-3'
style={{display : addedMovie ? '' : 'none'}}>
<h4>{addedMovie} added successfully</h4>
</div>
)
// const successMessage = () => {
// }
const addMovieForm = () => (
<form >
<span>Post photo</span>
<div className="form-group">
<label className="btn btn-block btn-success">
<input
onChange={handleChange("photo")}
type="file"
name="photo"
accept="image"
placeholder="choose a file"
/>
</label>
</div>
<div className="form-group">
<input
onChange={handleChange("movie_name")}
name="photo"
className="form-control"
placeholder="movie_name"
value={movie_name}
/>
</div>
<div className="form-group">
<input
onChange={handleChange("actor")}
name="photo"
className="form-control"
placeholder="actor"
value={actor}
/>
</div>
<div className="form-group">
<input
onChange={handleChange("duration")}
type="number"
className="form-control"
placeholder="duration"
value={duration}
/>
</div>
<div className="form-group">
<input
onChange={handleChange("country_of_origin")}
type="text"
className="form-control"
placeholder="country_of_origin"
value={country_of_origin}
/>
</div>
<div className="form-group">
<input
onChange={handleChange("director")}
type="text"
className="form-control"
placeholder="director"
value={director}
/>
</div>
<button type="submit" onClick={onSubmit} className="btn btn-success mb-2">
Add Movie
</button>
</form>
);
return (
<div>
<Navbar/>
<div className='container'style={{height:'0px'}}>
<Link to='/admin/dashboard'> <h1 className=' bg-info text-white p-4 text-decoration-none'>Admin Home</h1> </Link>
<div className='row bg-dark text-white rounded'>
<div className='col-md-8 offset-md-2'>
{successMessage()}
{addMovieForm()}
</div>
</div>
</div>
<Footer/>
</div>
)
}
export default AddMovie;
api call
This is my api request where frontend is talk with backend
import {API} from '../backend';
//add movie
export const addMovie = (userId,token,movie)=>{
return fetch(`${API}/movie/addMovie/${userId}`,{
method : "POST",
headers:{
Accept:'Application/json',
"Content-Type" : "application/json",
Authorization: `Bearer ${token}`
},
body:JSON.stringify(movie)
}).then(response => {
return response.json()
})
.catch(err => console.log(err))
}
//get all movie
export const getAllMovies = () => {
return fetch(`${API}/movies`,{
method : "GET"
})
.then(response => {
return response.json();
})
.catch(err => console.log(err))
}
//get a movie
export const getMovie = movieId =>{
return fetch(`${API}/movie/${movieId}`,{
method : "GET"
})
.then(response => {
return response.json();
})
.catch(err => console.log(err))
}
//update movie
export const updateMovie = (movieId,userId,token,movie)=>{
return fetch(`${API}/movie/${movieId}/${userId}`,{
method : "PUT",
headers:{
Accept:'Application/json',
Authorization: `Bearer ${token}`
},
body:movie
}).then(response => {
return response.json()
})
.catch(err => console.log(err))
}
//delete movie
export const deleteMovie = (movieId,userId,token)=>{
return fetch(`${API}/movie/${movieId}/${userId}`,{
method : "DELETE",
headers:{
Accept:'Application/json',
Authorization: `Bearer ${token}`
}
}).then(response => {
return response.json()
})
.catch(err => console.log(err))
}
##backend##
addmovie.js
This is backend addmovie logic where error occure
exports.addMovie = (req, res) => {
let form = new formidable.IncomingForm(); // declare a form
form.keepExtensions = true;
form.parse(req, (err, fields, file) => { //parse the form like err,fields,file
if (err) {
return res.status(400).json({
error: "Problem with image"
});
}
//destructure the field
const {movie_name,actor,country_of_origin,duration,director } = fields;
if (!movie_name || !actor || !country_of_origin || !duration || !director)
{
return res.status(400).json({
error: "please include all fields"
})
}
let movie = new Movie(fields);
//handle file here
if (file.photo) {
if (file.photo.size > 300000) {
return res.status(400).json({
error: "file size to big!"
})
}
movie.photo.data = fs.readFileSync(file.photo.path)
movie.photo.contentType = file.photo.type;
}
//save to the database
movie.save((err, movie) => {
if (err) {
res.status(400).json({
error: "saving movie in database failed"
})
}
res.json(movie);
})
})
}

Related

axios.get not working while am i searching product name

backend
const ProductListFilter = async (req, res) => {
try {
const productList = await productModel.find(req.query).collation({ locale: "en", strength: 2 });
return res
.status(201)
.send({
status: true,
message: `Total ${productList.length} product found `,
data: productList,
});
} catch (error) {
res.status(500).send({ status: false, message: error.message });
}
};
frontend
import axios from "axios";
import { useState } from "react";
const ProductListFilter = () => {
const [search, setSearch] = useState();
const handleChange = (e) => {
setSearch({ ...search, [e.target.name]: e.target.value });
};
const handleSubmit = async (e) => {
e.preventDefault();
await axios
.get(`http://localhost:5000/ProductListFilter`)
.then((res) => alert(res.data.message))
.catch((err) => console.log(err.response.data.message));
};
console.log(search);
return (
<div>
<form onSubmit={handleSubmit}>
<label htmlFor="search">
<input type="search" name="search" id="search" onChange={handleChange} />
<button type="submit">Submit</button>
</label>
</form>
</div>
);
};
export default ProductListFilter;
you need to add name in query param as shown below.
import axios from "axios";
import { useState } from "react";
const ProductListFilter = () => {
const [search, setSearch] = useState();
const handleChange = (e) => {
setSearch({ ...search, [e.target.name]: e.target.value });
};
const handleSubmit = async (e) => {
e.preventDefault();
await axios
.get(`http://localhost:5000/ProductListFilter?name=${search.name}`)
.then((res) => alert(res.data.message))
.catch((err) => console.log(err.response.data.message));
};
console.log(search);
return (
<div>
<form onSubmit={handleSubmit}>
<label htmlFor="search">
<input type="search" name="search" id="search" onChange={handleChange} />
<button type="submit">Submit</button>
</label>
</form>
</div>
);
};
export default ProductListFilter;

Unable to fetch data from Form using FormData

I am creating an 'edit profile' page for a dashboard the technologies that I use for the same are Next.js, Node.js & MongoDB.
Note: skip to the backend part if you just wanted to know the issue.
Frontend
Firstly,let me explain the Frontend part.
I am using useRef() inorder to reference data(name,bio) in the inputfields. which are working nicely.
Everything is fine the issue is in the handlesbumit() event_handler.
I am using FormData to send my form data to the backend API
If you're thinking why I'm not using a usual body object to send data the reason is that I have to add the profile picture updation later for which I have to send files , which as far I know we can't do that with an Object and yeah just to inform you it works fine if I would have used that Object part but can't use it with profilepicture updation.
The value that I have consoled out for the references are all good, and the rest of the handler is just as it is written can't find anything odd in that.
import { useUser } from '../../../lib/hooks';
import React, { useState, useEffect, useRef } from 'react';
import Head from 'next/head';
import { ImBook, ImListNumbered } from 'react-icons/im';
import { AiFillGithub, AiOutlineTwitter, AiFillFacebook, AiFillInstagram, AiFillLinkedin } from 'react-icons/ai'
import { FaFacebook, FaStackOverflow } from 'react-icons/fa';
const ProfileSection = () => {
const [user, { mutate }] = useUser();
const [isUpdating, setIsUpdating] = useState(false);
const nameRef = useRef();
const profilePictureRef = useRef();
const bioRef = useRef();
const [msg, setMsg] = useState({ message: '', isError: false });
useEffect(() => {
nameRef.current.value = user.name;
bioRef.current.value = user.Bio;
}, [user]);
const handleSubmit = async (event) => {
event.preventDefault();
if (isUpdating) return;
setIsUpdating(true);
console.log(nameRef.current.value); //Testing
console.log(bioRef.current.value); //Testing
const formData = new FormData();
formData.append('name', nameRef.current.value);
formData.append('Bio', bioRef.current.value);
console.log(formData.get('name'));
const res = await fetch('/api/user', {
method: 'PATCH',
body: formData,
});
if (res.status === 200) {
const userData = await res.json();
mutate({
user: {
...user,
...userData.user,
},
});
setMsg({ message: 'Profile updated' });
} else {
setMsg({ message: await res.text(), isError: true });
}
};
return (
<>
<Head>
<title>Settings</title>
</Head>
<main>
<div class="row">
<div class="col s12 m12">
<div className="card-panel br-10">
{msg.message ? <p style={{ color: msg.isError ? 'red' : '#0070f3', textAlign: 'center' }}>{msg.message}</p> : null}
<form onSubmit={handleSubmit}>
<div className="row">
<div className="col s12 m6 l6">
<label htmlFor="name">
Name
<input
required
id="name"
name="name"
type="text"
ref={nameRef}
/>
</label>
</div>
<div className="col s12 m6 l6">
<label htmlFor="bio">
Bio
<textarea
id="bio"
name="bio"
type="text"
ref={bioRef}
/>
</label>
</div>
</div>
<div className="center-align">
<button disabled={isUpdating} className="btn" type="submit" >Save</button>
</div>
</form>
</div>
</div>
</div>
</main>
</>
);
};
const SettingPage = () => {
const [user] = useUser();
if (!user) {
return (
<>
<p>Please sign in</p>
</>
);
}
return (
<>
<ProfileSection />
</>
);
};
export default SettingPage;
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
import { useUser } from '../../../lib/hooks';
import React, { useState, useEffect, useRef } from 'react';
import Head from 'next/head';
import { ImBook, ImListNumbered } from 'react-icons/im';
import { AiFillGithub, AiOutlineTwitter, AiFillFacebook, AiFillInstagram, AiFillLinkedin } from 'react-icons/ai'
import { FaFacebook, FaStackOverflow } from 'react-icons/fa';
const ProfileSection = () => {
const [user, { mutate }] = useUser();
const [isUpdating, setIsUpdating] = useState(false);
const nameRef = useRef();
const profilePictureRef = useRef();
const bioRef = useRef();
const [msg, setMsg] = useState({ message: '', isError: false });
useEffect(() => {
nameRef.current.value = user.name;
bioRef.current.value = user.Bio;
}, [user]);
const handleSubmit = async (event) => {
event.preventDefault();
if (isUpdating) return;
setIsUpdating(true);
console.log(nameRef.current.value);
console.log(bioRef.current.value);
const formData = new FormData();
formData.append('name', nameRef.current.value);
formData.append('Bio', bioRef.current.value);
console.log(formData.get('name'));
const res = await fetch('/api/user', {
method: 'PATCH',
body: formData,
});
if (res.status === 200) {
const userData = await res.json();
mutate({
user: {
...user,
...userData.user,
},
});
setMsg({ message: 'Profile updated' });
} else {
setMsg({ message: await res.text(), isError: true });
}
};
return (
<>
<Head>
<title>Settings</title>
</Head>
<main>
<div class="row">
<div class="col s12 m12">
<div className="card-panel br-10">
{msg.message ? <p style={{ color: msg.isError ? 'red' : '#0070f3', textAlign: 'center' }}>{msg.message}</p> : null}
<form onSubmit={handleSubmit}>
<div className="row">
<div className="col s12 m6 l6">
<label htmlFor="name">
Name
<input
required
id="name"
name="name"
type="text"
ref={nameRef}
/>
</label>
</div>
<div className="col s12 m6 l6">
<label htmlFor="bio">
Bio
<textarea
id="bio"
name="bio"
type="text"
ref={bioRef}
/>
</label>
</div>
</div>
<div className="center-align">
<button disabled={isUpdating} className="btn" type="submit" >Save</button>
</div>
</form>
</div>
</div>
</div>
</main>
</>
);
};
const SettingPage = () => {
const [user] = useUser();
if (!user) {
return (
<>
<p>Please sign in</p>
</>
);
}
return (
<>
<ProfileSection />
</>
);
};
export default SettingPage;
Backend
Now, the backend API for the same handlesubmit() event_handler i.e. 'api/user'
Please ignore the handler, it's just a predefined middleware npm next-connect which itself checks what type of request is coming if its 'PATCH' it will run handler.patch.
The Issue is the value of name & Bio is undefined,which means its not getting values from req.body;
And to check I also consoled out req.body which give out this
The data is correct but req.body is not a Object its a String now and I get it, its because I'm using formdata so how to get the values of name & Bio from this req.body ?
import nextConnect from 'next-connect';
import middleware from '../../../middlewares/middleware';
import { extractUser } from '../../../lib/api-helpers';
const handler = nextConnect();
handler.use(middleware);
handler.get(async (req, res) => res.json({ user: extractUser(req) }));
handler.patch(async (req, res) => {
if (!req.user) {
req.status(401).end();
return;
}
const { name, Bio } = req.body;
await req.db.collection('users').updateOne(
{ _id: req.user._id },
{
$set: {
name:name,
Bio: Bio,
},
},
);
res.json({ user: { name, Bio } });
});
export default handler;
I have encountered a this issue.
I was resolve it by use 2 form, a form use to get user's info as email, password and the other for send user's picture.
Maybe has best practice for this case.

bad request while submitting form

Hii i ma new in reactjs i am getting an error when i am trying to add movie , everything i wrote correctly . but dont know why this error came anyone explain and help to solve error
this img help you to catch error easily
img
https://ibb.co/bW5t0t8 and
https://ibb.co/Ky7MQgw
env REACT_APP_BACKEND=http://localhost:8000/api
export const API = process.env.REACT_APP_BACKEND;
adminapicall.js
this is my all api call where i communicate with backend
import {API} from '../backend';
//add movie
export const addMovie = (userId,token,movie)=>{
return fetch(`${API}/movie/addMovie/${userId}`,{
method : "POST",
headers:{
Accept:'Application/json',
Authorization: `Bearer ${token}`
},
body:movie
}).then(response => {
return response.json()
})
.catch(err => console.log(err))
}
//get all movie
export const getAllMovies = () => {
return fetch(`${API}/movies`,{
method : "GET"
})
.then(response => {
return response.json();
})
.catch(err => console.log(err))
}
//get a movie
export const getMovie = movieId =>{
return fetch(`${API}/movie/${movieId}`,{
method : "GET"
})
.then(response => {
return response.json();
})
.catch(err => console.log(err))
}
//update movie
export const updateMovie = (movieId,userId,token,movie)=>{
return fetch(`${API}/movie/${movieId}/${userId}`,{
method : "PUT",
headers:{
Accept:'Application/json',
Authorization: `Bearer ${token}`
},
body:movie
}).then(response => {
return response.json()
})
.catch(err => console.log(err))
}
//delete movie
export const deleteMovie = (movieId,userId,token)=>{
return fetch(`${API}/movie/${movieId}/${userId}`,{
method : "DELETE",
headers:{
Accept:'Application/json',
Authorization: `Bearer ${token}`
}
}).then(response => {
return response.json()
})
.catch(err => console.log(err))
}
add Movie.js
here i wrote my all addmovie logic
import React,{useState} from 'react';
import Navbar from '../pages/Navbar';
import Footer from '../pages/Footer';
import {Link} from 'react-router-dom';
import {isAuthenticated} from '../Auth/index';
import {addMovie} from '../Admin/adminapicall';
const AddMovie = () => {
const {user,token} = isAuthenticated();
const [values,setValues] = useState({
movie_name:'',
actor:'',
country_of_origin:'',
duration:'',
director:'',
photo:'',
loading:false,
error:'',
addedMovie:'',
getRedirect:false,
// formData:''
})
const {movie_name,actor,country_of_origin,duration,director,photo,loading,error,addedMovie,getRedirect} = values;
const handleChange = name => event => {
const value = name === "photo" ? event.target.files[0] : event.target.value
// formData.set(name,value);
setValues({...values,[name]:value})
};
const onSubmit = (e) => {
e.preventDefault();
setValues({...values,error:'',loading:true})
addMovie(user._id,token,JSON.stringify(values)).then(data =>{
if(data.error){
setValues({...values,error:data.error})
}else{
setValues({
...values,
movie_name:'',
actor:'',
country_of_origin:'',
duration:'',
director:'',
photo:'',
loading:false,
addedMovie: data.movie_name
})
}
})
}
const successMessage = () => (
<div className='alert alert-success mt-3'
style={{display : addedMovie ? '' : 'none'}}>
<h4>{addedMovie} added successfully</h4>
</div>
)
// const successMessage = () => {
// }
const addMovieForm = () => (
<form >
<span>Post photo</span>
<div className="form-group">
<label className="btn btn-block btn-success">
<input
onChange={handleChange("photo")}
type="file"
name="photo"
accept="image"
placeholder="choose a file"
/>
</label>
</div>
<div className="form-group">
<input
onChange={handleChange("movie_name")}
name="photo"
className="form-control"
placeholder="movie_name"
value={movie_name}
/>
</div>
<div className="form-group">
<input
onChange={handleChange("actor")}
name="photo"
className="form-control"
placeholder="actor"
value={actor}
/>
</div>
<div className="form-group">
<input
onChange={handleChange("duration")}
type="number"
className="form-control"
placeholder="duration"
value={duration}
/>
</div>
<div className="form-group">
<input
onChange={handleChange("country_of_origin")}
type="text"
className="form-control"
placeholder="country_of_origin"
value={country_of_origin}
/>
</div>
<div className="form-group">
<input
onChange={handleChange("director")}
type="text"
className="form-control"
placeholder="director"
value={director}
/>
</div>
<button type="submit" onClick={onSubmit} className="btn btn-success mb-2">
Add Movie
</button>
</form>
);
return (
<div>
<Navbar/>
<div className='container'style={{height:'0px'}}>
<Link to='/admin/dashboard'> <h1 className=' bg-info text-white p-4 text-decoration-none'>Admin Home</h1> </Link>
<div className='row bg-dark text-white rounded'>
<div className='col-md-8 offset-md-2'>
{successMessage()}
{addMovieForm()}
</div>
</div>
</div>
<Footer/>
</div>
)
}
export default AddMovie;
backend
addmovie.js
this is my backend addmovie logic
const Movie = require('../model/movie');
const formidable = require('formidable');
const_ = require('lodash');
const fs = require('fs');
exports.getMovieById = (req, res, next, id) => {
Movie.findById(id).exec((err, movie) => {
if (err) {
return res.status(400).json({
error: "Movie not found "
})
}
req.movie = movie;
next();
})
}
exports.addMovie = (req, res) => {
let form = new formidable.IncomingForm(); // declare a form
form.keepExtensions = true;
form.parse(req, (err, fields, file) => { //parse the form like err,fields,file
if (err) {
return res.status(400).json({
error: "Problem with image"
})
}
//destructure the field
const {movie_name,actor,country_of_origin,duration,director } = fields;
if (!movie_name || !actor || !country_of_origin || !duration || !director)
{
return res.status(400).json({
error: "please include all fields"
})
}
let movie = new Movie(fields);
//handle file here
if (file.photo) {
if (file.photo.size > 300000) {
return res.status(400).json({
error: "file size to big!"
})
}
movie.photo.data = fs.readFileSync(file.photo.path)
movie.photo.contentType = file.photo.type;
}
//save to the database
movie.save((err, movie) => {
if (err) {
res.status(400).json({
error: "saving movie in database failed"
})
}
res.json(movie);
})
})
}
I believe Backend is working properly
In fetch when you are sending body you must send it in string format, it seems a movie variable is an object, convert it to string and send
return fetch(`${API}/movie/addMovie/${userId}`,{
method : "POST",
headers:{
Accept:'Application/json',
Authorization: `Bearer ${token}`
},
body:JSON.stringify(movie)
}).then(response => {
Do this changes in all your fetch calls

How to send User to Next Page After form validation in react?

This in My SignUp Component, Im trying To send User to Signin Component If Username And Password Is correct.
this is Signup Code Below,
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import Axios from 'axios';
const initianValue = {
username: '',
password: '',
nameError: '',
passError: '',
dataError: '',
};
class SignUp extends Component {
constructor(props) {
super(props);
this.state = initianValue;
this.handleInputChange = this.handleInputChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleInputChange = (e) => {
this.setState({
[e.target.name]: e.target.value,
});
};
validForm() {
let nameError = '';
let passError = '';
let dataError = '';
const user = {
username: this.state.username,
password: this.state.password,
};
if (!this.state.username) {
nameError = 'Enter Name';
}
if (user.username !== '' && user.password !== '') {
Axios.post('http://localhost:9000/checkUser', user)
.then((res) => this.setState({ dataError: res.data }))
.catch((err) => console.log(err));
}
if (!this.state.password) {
passError = 'Enter Password';
}
if (nameError || passError || dataError) {
this.setState({
nameError,
passError,
dataError,
});
return false;
}
return true;
}
handleSubmit = (e) => {
e.preventDefault();
const isvalid = this.validForm();
if (isvalid) {
this.setState(initianValue, () => this.props.history.push('/SignIn'));
}
};
render() {
return (
<div className='Main'>
<span className='create'>Create Account</span>
<div className='SignUp'>
<form onSubmit={this.handleSubmit}>
<div className='form-group'>
<label>Username</label>
<input
type='text'
name='username'
value={this.state.username}
className='form-control'
onChange={this.handleInputChange}
/>
<div className='error'>
{this.state.nameError}
{this.state.dataError}
</div>
<br />
<label>Password</label>
<input
type='password'
name='password'
value={this.state.password}
className='form-control'
onChange={this.handleInputChange}
/>
<div className='error'>{this.state.passError}</div>
<br />
<button type='submit' className='btn btn-primary'>
Sign Up
</button>
</div>
</form>
</div>
<div className='signinForm'>
<label>
Already Have Account <Link to='/Signin'> Sign In </Link>
</label>
</div>
</div>
);
}
}
export default SignUp;
Its Works Perfect If I Put Right username and password but in wrong username / password its also send me to Signin Page and Shows warning in console like this
index.js:1 Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
in SignUp (created by Context.Consumer)
i wrap Both Component SignUp And Signin In Router,
this is my server.js file to send data if username and password is correct in database
app.post('/checkUser', function (req, res) {
const name = req.body.username;
const pass = req.body.password;
conn.query(
`SELECT * FROM users WHERE username = (?) AND password = (?) `,
[name, pass],
(err, rows) => {
if (err) throw err;
if (!rows.length) {
res.send('Wrong Data');
}
}
);
});
Your validForm makes an async call. By the time the async call is finished the validForm function as well as handleSubmit function execution is already completed. Then the then block is executed where you are setting state and therefore the error.
Solution: Make validForm an async function and await for your async call. Also make handleSubmit function an async and await for validForm.
Working demo
Code snippet
class SignUp extends Component {
constructor(props) {
super(props);
this.state = initianValue;
this.handleInputChange = this.handleInputChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleInputChange = e => {
this.setState({
[e.target.name]: e.target.value
});
};
async validForm() {
let nameError = "";
let passError = "";
let dataError = "";
const user = {
username: this.state.username,
password: this.state.password
};
if (!this.state.username) {
nameError = "Enter Name";
}
if (user.username !== "" && user.password !== "") {
await Axios.get("https://jsonplaceholder.typicode.com/todos/1", user) //fake api
.then(res => {
dataError = "user already exists"; //provide dynamic error..
//this.setState({ dataError: res.data }); // not required
})
.catch(err => console.log("err", err));
}
if (!this.state.password) {
passError = "Enter Password";
}
if (nameError || passError || dataError) {
this.setState({
nameError,
passError,
dataError
});
return false;
}
return true;
}
handleSubmit = async e => {
e.preventDefault();
const isvalid = await this.validForm();
if (isvalid) {
this.setState(initianValue, () => this.props.history.push("/SignIn"));
}
};
render() {
return (
<div className="Main">
<span className="create">Create Account</span>
<div className="SignUp">
<form onSubmit={this.handleSubmit}>
<div className="form-group">
<label>Username</label>
<input
type="text"
name="username"
value={this.state.username}
className="form-control"
onChange={this.handleInputChange}
/>
<div className="error">
{this.state.nameError}
{this.state.dataError}
</div>
<br />
<label>Password</label>
<input
type="password"
name="password"
value={this.state.password}
className="form-control"
onChange={this.handleInputChange}
/>
<div className="error">{this.state.passError}</div>
<br />
<button type="submit" className="btn btn-primary">
Sign Up
</button>
</div>
</form>
</div>
<div className="signinForm">
<label>
Already Have Account <Link to="/Signin"> Sign In </Link>
</label>
</div>
</div>
);
}
}
The issue could be on the handling of the response of the fetch. This is just a quick guess but try to not set the state of dataError and just modify the value of your variable dataError that you declared in this local function instead of the class variable. Does that make sense? when you check in your "if (nameError || passError || dataError)" you are checking for the local variable of your function and not the class which I think is fine but you aren't changing the variable if the response is an error.
Second if you change the setState and then check the state.dataError you might not get the updated value refresh yet in the function.
Let me know if that makes sense and if it works.

Cannot POST /Admin

I was connecting react with my api in node js, but when connecting to the login the only thing that appears is "Cannot POST / Admin"
I have used the Postman and it seems that the back part works because the token returns, but I think there is some problem in the connection between the two.
I am working on react, nodejs, redux and mongodb
interface IProps {}
interface IPropsGlobal {
setToken: (t: string) => void;
setName: (u: string) => void;
}
const Login: React.FC<IProps & IPropsGlobal> = props => {
const [username, setUsername] = React.useState("");
const [password, setPassword] = React.useState("");
const [error, setError] = React.useState("");
const updateUsername = (event: React.ChangeEvent<HTMLInputElement>) => {
setUsername(event.target.value);
setError("");
};
const updatePassword = (event: React.ChangeEvent<HTMLInputElement>) => {
setPassword(event.target.value);
setError("");
};
const signIn = () => {
fetch("http://localhost:3006/api/auth", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
username: username,
password: password
})
})
.then(response => {
if (response.ok) {
response
.text()
.then(token => {
console.log(token);
props.setToken(token);
props.setName(username);
});
} else {
setError("Usuario o ContraseƱa incorrectos");
}
})
.catch(err => {
setError("Usuario o ContraseƱa incorrectos.");
});
};
return (
<div>
<div className="section"></div>
<h5 className="indigo-text">Please, login into your account</h5>
<div className="section"></div>
<div className="container">
<div className="z-depth-1 grey lighten-4 row er" >
<form className="col s12" method="post">
<div className='row'>
<div className='col s12'>
</div>
</div>
<div className='row'>
<div className='input-field col s12'>
<input className='validate' name='email' id='email' value={username}
onChange={updateUsername}/>
<label >Enter your email</label>
</div>
</div>
<div className='row'>
<div className='input-field col s12'>
<input className='validate' type='password' name='password' id='password' value={password}
onChange={updatePassword} />
<label >Enter your password</label>
</div>
<label >
<a className='pink-text' href='#!'><b>Forgot Password?</b></a>
</label>
</div>
<br />
<div className='row'>
<button type='submit' name='btn_login' className='col s12 btn btn-large waves-effect indigo'
onClick={signIn}>Login</button>
</div>
</form>
</div>
</div>
Create account
</div>
);
};
const mapDispatchToProps = {
setToken: actions.setToken,
setName: actions.setName
};
export default connect(
null,
mapDispatchToProps
)(Login);
Postman returns the token
The api console shows me:
POST /api/auth - - ms - -
Connected successfully to server
In the Web page
Failed to load resource: the server responded with a status of 404 (Not Found)
I have used this code or a similar one before in other projects but I do not understand what happened to me this time
const md5 = require('md5');
// Connection URL
const mongoUrl = 'mongodb://localhost:27017';
// Database Name
const mongoDBName = 'ArdalesTur';
/* GET users listing. */
router.get('/', (req, res) => {
res.send('respond with a resource');
});
const secret = 'mysecret';
// para interactuar con la base de datos
router.post('/auth', (req, res) => {
mongo.MongoClient.connect(mongoUrl, (err, client) => {
assert.equal(null, err);
console.log('Connected successfully to server');
const db = client.db(mongoDBName);
const query = db.collection('Admin').find({
username: req.body.username,
password: md5(req.body.password),
});
query.toArray().then((documents) => {
if (documents.length > 0) {
const token = jwt.sign(
{
_id: documents[0]._id,
username: documents[0].username
},
secret,
// {
// expiresIn: 86400
// }
);
res.send(token);
} else {
res.status(400).send('Invalid credentials');
}
});
client.close();
});
});
here you have the api

Resources