user2466886 user2466886 - 1 month ago 13
Javascript Question

Cannot redirect to another page in PUT request for Node

I'm using Node and Express for the first time to make a simple website that conducts CRUD operations on a database. When I issue my put request I can't get the page to redirect to '/index' and I've run debugger for express and haven't seen anything abnormal, the page simply doesn't change. Any thoughts? Here's the code in server.js

app.set('view engine', 'ejs')

app.all('/', function(req,res){
var cursor = db.collection('jobs').find().toArray(function(err, results) {
res.render('index.ejs', {jobs: results})
})
})

app.get('/index',function (req, res) {
res.sendFile(__dirname + '/index.html');
})


app.get('/view',function (req, res) {
var cursor = db.collection('jobs').find().toArray(function(err, results) {

res.render('index.ejs', {jobs: results})

})
})

app.post('/jobs', function(req, res) {
db.collection('jobs').save(req.body,function(err, result){
if (err) return console.log(err)

console.log('saved to database');
res.redirect('/view');
})
})

app.put('/view', function(req, res) {
res.redirect(303, '/index');

})

Answer

An HTTP redirect just tells the client to get the data it asked for from somewhere else. It doesn't tell it to treat it any differently.

If you make an Ajax request and get a redirect response, then the browser will follow that redirect silently and return the contents of the new URL to your JavaScript.

The browser won't see the redirect and decide to load a new page in the viewport instead of presenting the data to your JavaScript.

If you want to load a new page after making your PUT request, then you need to wait for the response to come in and then (for example) assign a new value to window.location.href.