我正在嘗試在驗證注冊后重定向用戶。請參閱下面的代碼,它從未與我嘗試過的所有內容一起使用。我也試過前端部分
<Redirect=to"/login" />
這也不是成功。我正在嘗試重定向到:http://localhost:3000/login,后端當前在埠 5000 上。我還認為控制臺中出現了這些錯誤:
Access to XMLHttpRequest at 'http://localhost:3000/login' (redirected from '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.
GET http://localhost:3000/login net::ERR_FAILED
createError.js:16 Uncaught (in promise) Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:99)
我的第一個想法是標題沒有設定,但它在我的 app.js 中
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content, Accept, Content-Type, Authorization"
);
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, PATCH, OPTIONS"
);
next();
});
提前致謝
exports.signup = (req, res) => {
bcrypt.hash(req.body.password, 10).then((hash) => {
const user = {
lastName: req.body.lastName,
firstName: req.body.firstName,
email: req.body.email,
password: hash,
};
User.create(user)
.then(() => {
res.redirect(301, 'http://localhost:3000/login');
})
.catch((error) => res.status(500).json({ message: "Impossible de créer l'utilisateur. " error }));
});
};
uj5u.com熱心網友回復:
res.status(200).redirect('login');
(編輯)這將回傳 200 并從后端重定向用戶。
如果您愿意,這是我的前端解決方案。
在前端,您可以window.location.replace('/login')在 express 回傳值之后使用重定向到您想要的位置。
我的意思是在您在 Express API 上驗證用戶之后,回傳 200 viares.status(200).send()以讓您的前端知道該用戶可以被重定向。
jQuery 的一個例子:
前端
<script>
$.get('http://localhost:3000/login', function(data, status, jqXHR) {
if (status === 200) {
window.location.replace('redirect-location.html')
} else {
// What to do if the status isn't 200
}
})
</script>
后端:
app.get('/login', (res, req, err) => {
// Validate
const result = validatefunction() // true if login matches, false otherwise
if (result) {
res.status(200).send()
} else if (!result) {
res.status(400).send()
} else {
res.status(500).send()
}
})
希望我有所幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/316621.html
標籤:javascript 节点.js 表达 重定向
上一篇:我正在嘗試將/example重定向到Apache的httpd.conf中的example.html,但它不起作用
