Friday 20 January 2017

Update page from data sent from a Post request in Express

"I'm learning Express and I am trying to build something kinda like bit.ly's web page (The url shortener and stuff) Right now I can get the links to be displayed on page and everything but when I refresh the page the link is still there, it doesn't disappear until I restart the server; I can generate new links and it's replaced but if I refresh the page it doesn't go away."That was a problem that I had and someone answered me that it was because some variables were set to the global scope and when I changed their values they stayed like that after each refresh. I asked about what could be a fix for this so I can still pass the variables to the templating engine and change the value of these with the information of the post request and the answer was that I could make the postreturn a JSON object with the data instead of doing a redirect. Then do the POST async from the client and display the data.My question is how can I do that last part? The POST async from the client and display the data. This is my code. I could see the error that I was having before but I don't know exactly how can I keep the same behavior with the suggestion that I got.var data; var url; /* GET home page. */ router.get('/', (req, res, next) => { res.render('index', { 'data': data, 'url': url}); }); /* POST HANDLER */ router.post('/link', function(req, res, next) { url = req.body.link; bitly.shorten(url) .then(response => { data = response.data.url; res.redirect("/"); }); }); I was using a form but changed it to a jQuery request:$('#shortLink').on('click', () => { $.ajax({ type: 'POST', url: '/link', data: {link: $('#linkInput').val()}, success: data => { console.log(data); } }); }); And that's it. Hope someone can help me or tell me if I need to explain my issue more in depth. Thanks.

Submitted January 20, 2017 at 08:24PM by Aguxez

No comments:

Post a Comment