I’m trying to make a post request in frontend to make a user register, but I’m having an error "404 not found"
file server.js
const express = require('express');
const connectDB = require('./config/conn');
const app = express();
//conectando o banco de dados
connectDB();
//iniciando o middleware
app.use(express.json({extended: false}));
app.get('/', (req, res) => res.send('API rodando'));
//Definindo rotas
app.use('/api/users', require('./routes/api/users'));
app.use('/api/auth', require('./routes/api/users'));
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server iniciado na porta ${PORT}`))
file Registro.jsx
import React, { useState } from 'react';
import '../auth/Registro.css';
import { Link } from 'react-router-dom';
import axios from 'axios';
const Registro = () => {
const [formData, setFormData] = useState({
nome:'',
email:'',
senha: '',
senha2: ''
});
const { nome, email, senha, senha2 } = formData;
const onChange = e => setFormData({ ...formData, [e.target.name]: e.target.value });
const onSubmit = async e => {
e.preventDefault();
if(senha !== senha2){
console.log('As senhas devem ser iguais');
} else {
const newUser = {
nome,
email,
senha,
senha2
}
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 (
<div className='section_registro'>
<p> Página de registro! </p>
<form className='form' onSubmit={e => onSubmit(e)}>
<label> Insira seu nome completo </label>
<input
type="text"
name="nome"
value={nome}
placeholder='nome'
required
onChange={e => onChange(e)} />
<label> Insira seu email </label>
<input
type="email"
name="email"
value={email}
placeholder='email'
required
onChange={e => onChange(e)} />
<label> Insira sua senha </label>
<input
type="password"
name="senha"
value={senha}
placeholder='senha'
required
onChange={e => onChange(e)} />
<label> Confira sua senha </label>
<input
type="password"
name="senha2"
value={senha2}
placeholder='senha'
required
onChange={e => onChange(e)}
/>
<input type='submit' value='Registro' className='btn btn-primário'/>
</form>
<p> Já tem uma conta? </p> <Link to="/login"> Login </Link>
</div>
)
}
export default Registro
file users.js
const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const { check, validationResult } = require('express-validator');
const jwt = require('jsonwebtoken');
const config = require('config');
const User = require('../../models/User');
//@route POST api/users
//@desc Registro de user
//@acess Public
router.post('/', [
check('nome', 'Nome é obrigatório').notEmpty(),
check('email', 'Insira um email válido').isEmail(),
check('senha', "Senha é obrigatória").notEmpty(),
], async (req, res) => {
const errors = validationResult(req);
if(!errors.isEmpty()){
return res.status(400).json({ errors: errors.array() });
}
const { nome, email, senha, tipo } = req.body;
try {
let user = await User.findOne({ email });
if (user){
res.status(400).json({ errors: [{ msg: 'Esse user já existe' }] });
}
user = new User({
nome,
email,
senha,
tipo
});
const salt = await bcrypt.genSalt(10);
user.senha = await bcrypt.hash(senha, salt);
await user.save();
const payload = {
user:{
id:user.id
}
}
jwt.sign(
payload,
config.get('jwtSecret'),
{ expiresIn: 36000 }, (err, token) => {
if(err) throw err;
res.json({ token });
});
} catch (err) {
console.error(err.message);
res.status(500).send('Server error');
}
}
);
module.exports = router;
idk why the browser is showing this error. It’s seems like my frontend is not "finding" my backend.
error: GET http://localhost:3000/registro 404 (Not Found)
I tried change the folder of backend and the path in server.js, but it didn’t work. after that, I’m having the error that I can’t get the register router, but I had the error POST http://localhost:5000/api/users 404 (Not Found)
What I am doing wrong?
2
Answers
I understood what was happening. I didn't put the proxy on the client side. Now it's running as well. Thanks for help everyone
You have not defined any route for registro.
If you want to access it without route you need to make the folder, in which registro.jsx exists, public
You can do it using
app.use(express.static(folder-name));