Я пытаюсь войти в мое приложение стека mern, сзади кажется, что все в порядке, спереди, проблема в том, что, если я пытаюсь войти, он говорит, что у него есть проблемы с политикой CORS. Если я добавлю пакет cors на сервер, сервер не будет загружать данные.
Вот передняя часть
constructor(props){
super(props);
this.state = {
userName: '',
password: ''
};
}
handleInputChange = (event) => {
const {value, name} = event.target;
this.setState({
[name]: value
});
};
onSubmit = event => {
event.preventDefault();
fetch('http://localhost:5000/api/users/authenticate', {
method: 'POST',
body: JSON.stringify(this.state),
headers: {
'Content-Type': 'application/json'
}
}).then(res=>{
if (res.status === 200) {
console.log('hello world');
this.props.history.push('/');
}else{
const error = new Error(res.error);
throw error
}
}).catch(err => {
console.error(err);
})
};
а вот задняя часть
router.post('/authenticate', (req, res) => {
const { userName, password } = req.body;
if (!userName || !password) {
let msg = "Username or password missing!";
console.error(msg);
res.status(401).json({msg: msg});
return;
}
User.findOne({ userName })
.then(user => {
bcrypt.compare(password, user.password)
.then(isMatch => {
if(!isMatch) return res.status(400).json({ msg: 'Wrong password' });
jwt.sign(
{ id: user.id },
config.get('jwtSecret'),
{ expiresIn: 3600 },
(err, token) => {
if(err) throw err;
res.json({token, user: {
id: user.id,
userName: user.userName
}
});
}
)
})
})
});
Основной результат - просто войти в систему и удалить все проблемы с политикой cors. Спасибо за все советы!