Я работал с Cors ранее в приложении стека MEAN. И это прекрасно сыграло свою роль. Однако теперь, когда я перехожу к стеку MERN, я получаю эту ошибку, несмотря на использование CORS в бэкэнде:
Access to XMLHttpRequest at 'http://localhost:5000/api/users/register' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Register.js:43 Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:83)
xhr.js:178 POST http://localhost:5000/api/users/register net::ERR_FAILED
Так что по какой-то причине CORS не делает то, что должен делать?
Вот основной код:
Сервер / сервер. js
// Use routes
app.use("/api/users", users);
app.use("/api/profile", profile);
app.use("/api/posts", posts);
// Use Cors
app.use(Cors());
//process.env.Port is for Heroku
const port = process.env.Port || 5000;
// `` ES6 Template literal is used so that we can put a variable inside the String
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
Сервер / маршруты / API / пользователи. js
// @route POST api/users/register
// @desc Register user
// @access Public
router.post("/register", (req, res) => {
// Before we do anything, we will validate the data
const { errors, isValid } = validateRegisterInput(req.body);
// Check validation
if (!isValid) {
return res.status(400).json(errors);
}
// First, we will use mongoose to find if the email exists
// Because we don't want someone to register with an email that's already in the db
// req.body.email is possible thanks to bodyParser module
User.findOne({ email: req.body.email }).then(user => {
if (user) {
errors.email = "email already exists";
return res.status(400).json({
errors
});
} else {
const avatar = gravatar.url(req.body.email, {
s: "200", //Size
r: "pg", //Rating
d: "mm" //Default
});
// new Modelname({data})
const newUser = new User({
name: req.body.name,
email: req.body.email,
// This will be the avatar URL
//avatar: avatar,
// Since they are the same with ES6 we can do just avatar
// But it doesn't know what avatar is, for this we will use gravatar
avatar,
password: req.body.password
});
bcrypt.genSalt(10, (err, salt) => {
// If there's an error it'll give us an error, if not it'll give us a hash
// A hash is what you want to store in the database
bcrypt.hash(newUser.password, salt, (error, hash) => {
if (error) {
throw error;
}
newUser.password = hash;
newUser
.save()
.then(user => res.json(user))
.catch(err => {
console.log(err);
});
});
});
}
});
});
Фронтенд / src / components / auth / Register. js
axios
.post("http://localhost:5000/api/users/register", newUser)
.then(res => {
console.log(res.data);
})
.catch(err => console.log(err));