I'm trying to show webpage to users at the route app.get(/:transactionid) with the text telling them "Please wait, your file is processing"
And after file processing is finished (could take around 5-10 seconds) then change that text to "Your file is ready, download here"
But I don't really know how to pass variable from app.post to app.get.
The variable is just aws-s3 download link (if that matters).
I have 2 routes like so:
app.get('/:transactionid', async (req,res)=>{
res.render('purchase')
})
app.post('/:transactionid', async (req,res)=>{
// some file processing and uploading to aws-s3
const url = s3url;
res.render('purchase',{link:url})
})
and in the ejs view I have:
<body>
<% if(link) { %>
Your file is ready <div class="inline text-blue-600">Download here </div>
<% } else { %>
<div class="text-red-500">Please wait, your file is processing</div>
<% } %>
</body>
But the res.render('purchase',{link:url}) in app.post won't update the text in the browser. I'm not sure if I understand correctly but I think I should send the url from app.post to app.get?
EDIT:
Here are some snippets of what it looks like uploading and inserting it into database
var params = {
Bucket: 'xxxxxxx',
Key: decodeURIComponent(awskey),
Body: buff };
// upload to s3
var uploadfile = s3.upload(params, function(err, data) {
if(err) {console.log(err);}
});
// turn it into promise
var promise = uploadfile.promise();
promise.then( function(data){
pool.query(`
INSERT INTO transactions (transactionid, s3url)
VALUES ($1, $2)
`, [transactionid, data.Location], (err, results) => { // data.Location is the s3 url
if (err) {
throw err;
}
});
})
Related
I'm trying to create a small multi-language project using NodeJS version 10.15.1, AngularJS version 1.5.8 and UTF8 encoded html. I should proceed with my own function instead of using other modules.
I created 2 different json files containing 2 different languages. The json is loaded via server using a $http call and the answer is stored inside a $scope variable.
$http.post(apihost + '/languages/language_frontend', {page: "home"}).then(function(language) {
$scope.language = language.json;
});
I pass the parameter page to filter with part of the json the function should retrieve.
router.post('/language_frontend', function(req, res, next) {
return new Promise(function(resolve,reject) {
if(config.language == 'it') return res.json({status: 'ok', json: italian_frontend[req.body.page]});
else if(config.language == 'en') return res.json({status: 'ok', json: english_frontend[req.body.page]});
});
});
This is (part) of one of the json
{
"home": {
"planning": "Pianificazione",
"activities_planning": "Pianificazione Attività"
},
"login": {
"test_one": "italiano uno",
"test_one": "italiano due"
}
}
And this is the html that displays the information
<div class="panel-heading">
<div class="row">
<div class="col-xs-3"><i class="fa fa-mobile-phone fa-5x"></i></div>
<div class="col-xs-9 text-right">
<div class="huge ng-binding">{{language.activities_planning}}</div>
</div>
</div>
</div>
The problem is that the displaying of activities_planning comes with an accented character and, coming from server side call, I don't know how to display it correctly. I'd like a general solution to implement everywhere, so I don't have to worry about few exceptions with special characters.
This is the result without a solution: Pianificazione Attivit�
Any suggestion?
So, here it is https://glitch.com/edit/#!/angularjs-specialchars. I tried to set up the same thing with you :
In my app.js on the backend, I get the content of JSON file and expose it in /language route :
const path = require("path");
const express = require("express");
const app = express();
const language = require("./test.json");
app.use('/', express.static(path.join(__dirname, 'public')));
app.get('/language', (req, res) => res.json({ status: "ok", json: language }));
app.listen(5000, function() {console.log("Server is running on port 5000")});
In my index.js on the client-side, I send a request to the server to get the JSON file :
angular.module("app", []).controller("MyController", ["$scope", "$http",
function ($scope, $http) {
// send request to get the json
$http.get('/language').then(function (resp) {
const language = resp.data.json;
console.log(language); // I've checked on the console.log, the text is OK
$scope.text = language.test; // bind to screen
});
}
]);
And in my index.html I just use it :
<body ng-app="app">
<div ng-controller="MyController">
<h1>Hello {{text}}!</h1>
</div>
</body>
What I have :
I am using Express for routing and MongoDB for my simple Node blog app (I'm new and just learning) and I need to redirect to the home page if somebody enters the incorrect URL, whenever it attempts to redirect the program crashes.
Terminal Output:
Server started on 3000
Rendered homepage
events.js:174
throw er; // Unhandled 'error' event
^
TypeError: Cannot read property 'postTitle' of null at line 115
Router Params / Get
//=== DYNAMIC POSTS ROUTE ===//
app.get("/posts/:postId", function(req, res){
const requestedPostTitle = req.params.postId;
Post.findOne({postTitle: requestedPostTitle}, function(err, foundPost){
if (!err) {
//FAILS HERE IF INCORRECT URL IS ENTERED INTO BROWSER
const title = foundPost.postTitle;
const date = foundPost.postDate;
const content = foundPost.postBody;
/*res.send(foundPost.postDate);*/
res.render(`post`, {
title: title,
date: date,
content: content
});
} /*else {
res.redirect(`/`);
console.log(`404 ${requestedPostTitle} does not exist`);
} */
});
});
The program will only crash if I type in an incorrect URL, after that, none of my pages will reload (I'm assuming because of the (err) callback), I have to restart my server manually and everything works again, nodemon doesn't reset it when it fails.
root view:
<h1>HOME</h1>
<p><%= pageStartContent %></p>
<% posts.forEach(function(post){ %>
<div class="post-box">
<h3><%= post.postTitle %></h3>
<p class="date"><%= post.postDate %></p>
<p class="post-body"><%= post.postBody.substring(0,450) + "..." %></p>
Read More
</div>
<% }) %>
app.get("/posts/:postId", function(req, res){
const requestedPostTitle = req.params.postId;
Post.findOne({postTitle: requestedPostTitle}, function(err, foundPost){
if (!err && foundPost) {
//FAILS HERE IF INCORRECT URL IS ENTERED INTO BROWSER
const title = foundPost.postTitle;
const date = foundPost.postDate;
const content = foundPost.postBody;
/*res.send(foundPost.postDate);*/
return res.render(`post`, {
title: title,
date: date,
content: content
});
}
return res.redirect(`/`);
});
});
the code didn't work before (maybe) because you are checking if there an error and if not rendering post but this does not mean that the post was found, you need to check if foundPost is not null.
I am new to Express and MongoDB. I created a small web app in Node.js and am using Express.js and Mongoose. I can succesfully create a user and have a user sign in but I am having trouble with a user being able to delete their account.
I have a user.js file in my routes folder which is where I am writing the code to signup, signin, delete, etc. Here is a link to the project on GitHub ( https://github.com/NicholasGati/shopping-cart-2 ). The button to delete a user's account is in views/user/edit.hbs. I put the button in a form. When I click the button, the user is not deleted and I am redirected to '/' for some reason. Note: '/:id' in my routes/user.js file becomes '/user/:id'.
Here is the code in the routes/user.js file for the delete method:
router.delete('/:id', isLoggedIn, (req, res, next) => {
User.findOneAndRemove({_id: req.params.id}, (err) => {
if (err) {
req.flash("error", err);
return res.redirect("/user/edit");
}
req.flash("success", "Your account has been deleted.");
req.logout();
return res.redirect("/shop/coffee");
});
});
Here is the form in views/user/edit.hbs:
<form action="/user/{{user.id}}" method="delete">
<div class="form-group">
<button type="submit" class="btn btn-danger">Delete Account</button>
</div>
</form>
Also, here is the isLoggedIn function:
function isLoggedIn(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.redirect("/");
}
Since you are new I think I should lead you to find the problem yourself:)
Make sure about form methods.
Make sure the route for user deletion is called.
If the markup doesn't seem right I am sorry cas I am using my phone to post this answer.
I had this exact same issue. I used an XMLHttpRequest from the client side in order to do this. I'm sorry I'm not experienced enough to explain why it worked this way and not from the node end, but it may have to do with form data being inherently designed to pass information, not delete information. In any case, try this solution.
In your client side code:
Your button code (form action shouldn't matter, and for that matter, the tag shouldn't either, since the logic is handled in the JS, but this is what I used):
<button id = "del-btn" class="btn btn-danger">Delete</button>
Script to send HTTP request from the button click, this code should go in the same file as your button above, or as an include JS file that the HTML page has imported:
<script>
var del_btn = document.getElementById("del-btn");
del_btn.addEventListener("click", function(e) {
var user = <%- JSON.stringify(user) %>;
var xhr = new XMLHttpRequest();
xhr.open("DELETE", "/user/" + user._id);
xhr.onreadystatechange = function () {
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
console.log(xhr.responseText);
window.location.href = "/users";
}
};
xhr.send();
//make XMLHttpRequest to delete the poll here
}, false);
</script>
in your server side route, note how the response is just a success code. It's the XMLHTTP Request from the client side that does the redirection:
app.delete('/user/:id', isLoggedIn, function(req,res){
User.remove({
_id: req.params.id,
ownerID: req.user._id
}, function (err, user) {
if (err)
return console.error(err);
console.log('User successfully removed from polls collection!');
res.status(200).send();
});
});
I have an HTML page which provides input fields for email ID and password, I use these values to connect with my backend SQL server through node js express application .
I have an app.post() method to connect with SQL.
app.post('/user', function (req, res, body) {
uid = req.body.user1;
pwd = req.body.user2;
config = 'Server={ip of server};Database=Dbname;Uid=domain\\user' + uid + ';Pwd=' + pwd;
var dbConn = new sql.Connection(config);
dbConn.connect().then(function () { //using promises instead of callbacks(onceconnect() is done), then go to then()
var request = new sql.Request(dbConn);
console.log('DONE');
res.status(500).json({ status: 'done' })
}).catch(function (err) {
console.log("INVALID");
res.status(500).json({ status: 'invalid' })
});
What I want to achieve is -
If the credentials are valid, displaying an alert 'DONE' at client side.
If the credentials are invalid, displaying an alert 'INVALID' at client side.
Currently, if everything is valid, there is DONE at /user.
If the ID and Password do not match, there is INVALID at /user.
My client side code is
<!DOCTYPE html>
<html>
<body>
<form id ="target" action="/user" method="post">
UserID : <input id="uid" type="text" name="user1" /> <!text fields for date input>
Password : <input id="pwd" type="password" name="user2" />
<input id="Submit1" type="submit" value="LOGIN"/> <!--<!submit button>-->
<input id="Button" type="button" value="show graphs" onclick="btntest_onclick()" />
</form>
$.post("/user", function (data) {
$("#target").html(data)
alert( "Data Loaded: " + data );
});
<script type="text/javascript">
function btntest_onclick() {
setTimeout(function () {
window.location.href = "/../";
},500);
}
</script>
</body>
</html>
I am unable to use $.post() on client to retrieve data back from user- gives 500 error.
How do I proceed? Please help me.
I could solve this by using the jquery ajax callback that returns back data to the client.
$("#target").submit(function (event) {
var formData = {
'uid': $('input[name=uid]').val(),
'pwd': $('input[name=pwd]').val()
};
$.ajax({
type: 'POST', // define the type of HTTP verb we want to use (POST for our form)
url: '/user', // the url where we want to POST
data: formData, // our data object
dataType: 'json', // what type of data do we expect back from the server
encode: true
})
.error(function (data) {
// log data to the console so we can see
alert(data.responseText);
})
.done(function (data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
});
event.preventDefault();
});
I'm using this on server side:
app.get('/getdata', function(request, response) {
client.query("SELECT time, name, assembly FROM timings order by time limit 10", function(err, results) {
console.log(results.rows[0]);
if (err) {
throw err;
}
}
//here i want to do something to send results to my html page
});
And this on client side html page
<form action="/getdata" method="get">
<input type="submit" value="Submit" ></input>
</form>
Also, help me with how I can display data on the same HTML page. And where i have to place my code because i'm new to nodejs.
Your code could look something like this:
app.get('/getdata', function(request, response) {
client.query("SELECT time, name, assembly FROM timings order by time limit 10", function(err, results) {
if (err) {
throw err;
}
response.send(results.rows); // assumes 'results.rows' can be serialized to JSON
});
});
You can retrieve that information from your HTML page using an AJAX-request. Let's assume you use jQuery (error handling not included):
$.getJSON('/getdata', function(response) {
// do something with the response, which should be the same as 'results.rows' above
});