Я создаю проект стека MERN, в котором мне нужно выполнить регистрацию и запросы на вход.
Я не могу сделать запрос POST со стороны клиента, он выдает ошибку.
`
Access to XMLHttpRequest at 'http://localhost:5000/users/signup' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Signup.js:49 Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:83)
xhr.js:178 POST http://localhost:5000/users/signup net::ERR_FAILED
`
Коды -
cors. js
const cors = require("cors");
const whitelist = [
"http://localhost:3000",
"https://localhost:3443",
"http://localhost:3001"
];
var corsOptionsDelegate = (req, callback) => {
var corsOptions;
console.log(req.header("Origin"));
if (whitelist.indexOf(req.header("Origin")) !== -1) {
corsOptions = { origin: true };
} else {
corsOptions = { origin: false };
}
callback(null, corsOptions);
};
exports.cors = cors();
exports.corsWithOptions = cors(corsOptionsDelegate);
узел user.router. js
...
const cors = require("../auth/cors.js");
const userRouter = express.Router(); // initialize express router
userRouter
.post("/signup", cors.corsWithOptions, (req, res, next) => {
console.log(req.body);
User.register(
new User({
username: req.body.username,
email: req.body.email,
firstName: req.body.firstName,
lastName: req.body.lastName
}),
req.body.password,
(err, user) => {
if (err) {
res.statusCode = 500;
res.setHeader("Content-Type", "application/json");
res.json({ err: err });
} else {
if (req.body.firstName) user.firstName = req.body.firstName;
if (req.body.lastName) user.lastName = req.body.lastName;
user.save((err, user) => {
if (err) {
res.statusCode = 500;
res.setHeader("Content-Type", "application/json");
res.json({ err: err });
return;
}
passport.authenticate("local")(req, res, () => {
res.statusCode = 200;
res.setHeader("Content-Type", "application/json");
res.json({ success: true, status: "Registration Successful!" });
});
});
}
}
);
})
...
реагирует на signup.component. js
signup = e => {
if (!isEmpty) {
const newUser = this.state.userDetail;
console.log(newUser);
this.setState({ loadingIsTrue: true });
// axios
// .get(process.env.REACT_APP_API_BASE_URL + "users/list")
// .then(res => console.log(res))
// .catch(err => console.log(err));
axios
.post(process.env.REACT_APP_API_BASE_URL + "users/signup", {
...newUser
})
.then(res => console.log(res))
.catch(err => console.log(err));
} else alert("Please fill all the details first to signup");
};
Примечание: когда запрос сделан из POSTMAN, он успешен, и база данных обновлена правильно