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('ошибка сервера');
}
}
);
CodePudding user response:
You're getting a 403
error code which means not found. You are also posting your /api/auth
routes so I'm assuming you want to post to auth but here: http://localhost:3000/api/users 403 (Forbidden)'
you are posting to /api/users
when you should be posting to /api/auth
.
If you are trying to post to users like your path suggests, then I recommend looking at your /api/users
routes and make sure you have a POST route configured. Otherwise, you will get a 403
error like you are receiving now.
CodePudding user response:
first of all i didn't understand that when you are sending request with postman to your backend it is working fine or not
but after being sure that you are sending request to the correct url
in first step try the request from another browser if postman working fine and if it works with another browser search for specific problem with the browser
step 2 why you are using port 8080 its any device default port iam not sure but it may cause some problems
and in final step try this app.use(cors({ origin : '*'}))
it means that requests can be sent to your backend from any addresses