so, my react frontend is on http://localhost:3000/ and express backend is on http://localhost:8080/
when i try to submit registration form, chrome console returns an error: 'POST http://localhost:3000/api/users 403 (Forbidden)'
i did some research here on stack and found out that i should use cors
, but all exact advices never helped
(i'm really sorry if the whole problem is actually easy, that's my first both react and express project if that makes any difference)
so i'd be really glad if someone just tell me what exact lines of code did i miss and where should i put it
also, i've already tested it with postman, everything work's fine on server side
here's my backend:
server.js
const express = require('express');
const connectDB = require('./config/db');
const cors = require('cors');
const app = express();
// connect database
connectDB();
// init middleware
app.use(express.json({ extended: false }));
// init cors
app.use(cors());
app.get('/', (req, res) => res.send('приложение запущено'));
// define routes
app.use('/api/users', require('./routes/api/users'));
app.use('/api/auth', require('./routes/api/auth'));
app.use('/api/posts', require('./routes/api/posts'));
app.use('/api/profile', require('./routes/api/profile'));
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => console.log(`сервер запущен, порт: ${PORT}`));
/api/auth.js
router.post(
'/',
[
check('email', 'пожалуйста, введите email').isEmail(),
check('password', 'пожалуйста, введите пароль').exists(),
],
async (req, res) => {
// валидация формы
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
console.log('успешная валидация данных в форме');
const { email, password } = req.body;
console.log(
'получены: email — "' + email + '" и пароль — "' + password + '"'
);
try {
// проверка наличия пользователя
let user = await User.findOne({ email });
if (!user) {
return res
.status(400)
.json({ errors: [{ msg: 'неверные логин и/или пароль' }] });
}
// проверка пароля
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
return res
.status(400)
.json({ errors: [{ msg: 'неверные логин и/или пароль' }] });
}
console.log('логин и пароль подходят');
// вебтокен
const payload = {
user: {
id: user.id,
},
};
jwt.sign(
payload,
config.get('jwtSecret'),
{ expiresIn: 360000 }, // поставить 3600 перед деплоем
(error, token) => {
if (error) throw error;
res.json({ token });
console.log('пользователю присвоен токен — ' + token);
}
);
} catch (error) {
console.error(error.message);
res.status(500).send('ошибка сервера');
}
}
);