I have an ajax post call and I want to just send the form values without waiting for a response to come. I want to redirect from my express app and not form my client side. server-side:
router.post("/", (req, res)=>{
res.status(200).send(`signup/confirm-email?v=${req.body.email}`);
// i want to be able to rediect with res.redirect("signup/confirm-email?v=${req.body.email}")
};
});
client-side:
$.post('/signup', $('#signup-form-container form').serialize())
.done(lnk=>{
window.location.replace(`${window.location}${lnk}`); })
.fail(function(xhr){ //handle errors };
The code above works, it sends a response to ajax and then i redirect from client side.
I want to redirect from server-side.
I tried to redirect from my express app using res.redirect() but it doesn't work without logging any errors to the console and in the network tab in the dev tool, it shows that the request type is xhr. If there isn't a solution to this problem, than is there a way to hide the query in the route recieved. I don't want v=${req.body.email}
to be displayed in the url bar. Thank you in advance.
Avoid using jQuery, it will almost always lead to bad practices and unmaintainable code.
You should use plain Javascript or React if you need a framework (which is mainly if you need to work on a big project, but may not be suited for total JS beginner). My solution here is in plain Javascript.
As a replacement for the jQuery request util ($.post()
, etc ...), browsers have a very good HTTP request API named fetch (MDN). I use it in this solution.
If you don't want to show the email
param in the URL, you can set it in the localStorage
.
You cannot redirect directly from Express for a POST
method. Only if you were trying to GET
a page, Express could redirect to another GET
(and so change the URL in your browser).
The only solution to your need is to use the window.location
after receiving the response from your /signup
endpoint.
Server-side:
router.post('/', function (req, res) {
const form = req.body.form
// your registration code here
// ...
res.json({
success: true,
email: form.email
})
})
Client-side:
signup.js
const form = {
email: document.getElementById('email').value
// add other fields you need
}
fetch('/signup', {
method: 'POST',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({ form })
})
.then(res => res.json())
.then(res => {
// Set the localStorage item so you can get it back
// in the JS script of /signup/confirm-email
localStorage.setItem('email', res.email)
// Redirect to the confirm email page
window.location = '/signup/confirm-email'
})
Client-side:
confirmEmail.js
const email = localStorage.getItem('email')
if (!email) window.location = '/signup'
// proceed with your code