I am building a nodejs, reactjs app and i am having issues for making requests from my reactjs part of the app to my API. I am using concurrently, so i made a proxy:
"proxy":"http://localhost:5000/"
Port 5000 is where my API is running and Port 3000 is where my ReactJs runs.
When i try to register a new user i get the following error
Cannot POST api/users
And my console shows what url is trying to request http://localhost:3000/api/users
But instead it should be http://localhost:5000/api/users
This is my Register.js:
import React, { Fragment, useState } from 'react'
import axios, { Axios } from 'axios';
const Register = () => {
const [formData, setFormData] = useState({
name:'',
email: '',
password: '',
password2: ''
});
const { name, email, password, password2 } = formData;
const onChange = e => setFormData({
...formData, [e.target.name]:e.target.value
});
const onSubmit = async e => {
e.preventDefault();
if(password !== password2){
console.log('Passwords do not match')
} else {
const newUser = {
name,
email,
password
}
try {
const config = {
headers:{
'Content-type': 'application/json'
}
}
const body = JSON.stringify(newUser)
const res = await axios.post('api/users', body, config);
console.log(res.data);
} catch (error) {
console.error(error.response.data)
}
}
}
return (
<Fragment>
<section className='container'>
<h1 className="large text-primary">Sign Up</h1>
<p className="lead"><i className="fas fa-user"></i> Create Your Account</p>
<form className="form" action="create-profile.html" onSubmit={e => onSubmit(e)}>
<div className="form-group">
<input type="text"
placeholder="Name"
name="name"
value={name}
onChange={e => onChange(e)}
required />
</div>
<div className="form-group">
<input type="email"
placeholder="Email Address"
name="email" value={email}
onChange={e => onChange(e)}
required/>
<small className="form-text"
>This site uses Gravatar so if you want a profile image, use a
Gravatar email</small
>
</div>
<div className="form-group">
<input
type="password"
placeholder="Password"
name="password"
minLength="6"
value={password}
onChange={e => onChange(e)}
required
/>
</div>
<div className="form-group">
<input
type="password"
placeholder="Confirm Password"
name="password2"
minLength="6"
value={password2}
onChange={e => onChange(e)}
required
/>
</div>
<input type="submit" className="btn btn-primary" value="Register" />
</form>
<p className="my-1">
Already have an account? <a href="login.html">Sign In</a>
</p>
</section>
</Fragment>
)
}
export default Register
And this is my users.js
//@route POST api/users
//@desc Register user
//@access public
router.post('/', [
check('name', 'Name is required')
.not()
.isEmpty(),
check('email', 'Plese include a valid email').isEmail(),
check('password', 'Please enter a password with 6 or more characters').isLength({min:6})
],
async (req, res)=> {
const errors = validationResult(req);
if(!errors.isEmpty()){
return res.status(400).json({ errors:errors.array()}); //400 is for bad requests
}
const { name, email, password } = req.body;
try{
//See if user exists
let user = await User.findOne({ email });
if(user){
return res.status(400).json({ errors: [{ msg:'User already exists' }] });
}
//Get users gravatar
const avatar = gravatar.url(email,{
s:'200',
r:'pg',
d:'mm'
})
user = new User({
name,
email,
avatar,
password
});
//Encrypt password
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(password, salt);
await user.save();
//Return jsonwebtoken -> this for users to be logged in right after registration
const payload = {
user:{
id: user.id
}
}
jwt.sign(
payload,
config.get('jwtSecret'),
{expiresIn: 360000}, //change to 3600 for production
(err, token)=>{
if(err) throw err;
res.json({ token });
}
)
}catch(err){
console.error('err.message');
res.status(500).send('Server Error');
}
});
module.exports = router;
What am i doing wrong? What is the solution to this error?