Uploading file to EC2 Web Server from Web Application - node.js

I am creating a simple application using Sails.js. What it basically does is it creates a new Item then saves it to the database and uploads the image to S3.
Here's what happens:
When I run my application on my local, it behaves okay. The req.body has contents, and the req.file('item-image') is not empty.
I am running it on EC2 now, and the problem is, the req.body is just an empty object, but the req.file('item-image') is not empty. I've tried different debugging scenarios, see them below:
If I remove the enctype="multipart/form-data" (I know this is needed for file upload, just trying), I get the req.body object that I expect, but as expected, the req.file('item-image') is empty.
I put back the enctype="multipart/form-data" then tried sending the request without the file, I get my expected req.body object.
I included an image on my request, the req.body object is empty, but the req.file('item-image') isn't.
The weirdest part is, when I send my request through postman, all behaves as expected. I'm really lost now, see my code below:
create_event.ejs
<form action=<%= event.createUrl %> method="POST" id="form-item" enctype="multipart/form-data">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="blue bigger">Please fill the following form fields</h4>
</div>
<div class="modal-body overflow-visible">
<div class="row">
<div class="col-xs-12 col-sm-5">
<div class="space"></div>
<input type="file" name="item-image"/>
</div>
<div class="col-xs-12 col-sm-7">
<div class="form-group">
<label for="form-field-username">Name</label>
<div>
<input class="input-large" type="text" id="form-field-username" placeholder="Item Name" name="item-name" />
</div>
</div>
<div class="space-4"></div>
<div class="form-group">
<label for="form-field-username">Description</label>
<div>
<input class="input-large" type="text" id="form-field-username" placeholder="Item Description" name="item-description"/>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-sm" data-dismiss="modal">
<i class="icon-remove"></i>
Cancel
</button>
<button class="btn btn-sm btn-primary" id="save-item">
<i class="icon-ok"></i>
Save
</button>
</div>
</div>
</div>
</form>
create_event.js
$('#save-item').on('click', function(e){
var response = confirm('Are you sure you want to continue saving this item?');
if(response == true) {
$('#form-item').submit();
}
});
AdminController.js
createItem: function(req, res){
console.log('Saving..');
console.log(req.body);
var eventId = req.path.split('/')[4];
req.file('item-image').upload(function callback(error, uploadedFile){
if(error) {
console.log(error);
return res.serverError();
}
console.log(uploadedFile);
s3Helper.upload(uploadedFile[0], function(error, data){
if(error) {
return res.serverError();
}
var item = {
ITEM_ID: uuid.v1(),
EVENT_ID: req.path.split('/')[4],
NAME: req.body['item-name'],
DESCRIPTION: req.body['item-description'],
IMAGE_URL: data.Location
}
EventItem.create(item, function(error, data){
if(error) {
console.log(error);
return res.serverError();
}
console.log('Successfully saved data: ');
console.log(data);
return res.redirect('/admin/events/' + eventId);
});
});
});
},
Thank you!

I found the answer here https://github.com/balderdashy/sails/issues/2508
Apparently, sails.js uses skipper and is sensitive on the order of the input. I just put the file part on the end and it now works.
I'm just confused as to why it works on my local, and not on my ec2 server.

Related

Update Operation in MongoDB with NodeJs

I am working on a Blog WebSite with CRUD operation I am able to achieve CRD operations but have issues with update One.
Issue:-
When I click on the edit button it opens the compose tab with the textfile loaded successfully but when I click on update it redirects to the home page but nothing Update, Please help me get out from this.
//This is the code for edit & Update Route
app.get("/posts/:postId/edit", (req, res) => {
Post.findById(req.params.postId, (err, post) => {
if (err) {
console.log(err);
} else {
res.render("edit", { post: post });
}
});
});
app.post("/posts/:postId/edit", (req, res) => {
Post.findByIdAndUpdate(
req.params.postId,
{
$set: {
title: req.body.title,
content: req.body.content,
},
},
(err, update) => {
if (err) {
console.log(err);
} else {
console.log("Post Updated");
res.redirect("/");
}
}
);
});
Form for the Edit/Update
//This is the Edit ejs file containing the update form
<form action="/posts/<%=post._id%>/edit/?_method=PUT" method="post">
<div class="mb-3">
<label for="post-title">Title</label>
<input class="form-control" id="post-title" name="postTitle" type="text" placeholder="Input title"
required autocomplete="off" value="<%=post.title%>">
</div>
<div class="mb-3">
<label for="postcontent">Post</label>
<textarea class="form-control text-area" id="postcontent" name="blog" rows="4" cols="50" required
placeholder="Start writing your blog ..............."><%=post.content%></textarea>
</div>
<button class="btn btn-primary publish-btn" type="submit" name="button">Update</button>
</form>
Your error is from the Ejs
You didn’t rename your req.body well to match your incoming data
You were meant to be used title instead of postTitle
And content instead of blog
Just edit your ejs to this and test gee
<form action="/posts/<%=post._id%>/edit/?_method=PUT" method="post">
<div class="mb-3">
<label for="post-title">Title</label>
<input class="form-control" id="post-title" name=“title" type="text" placeholder="Input title"
required autocomplete="off" value="<%=post.title%>">
</div>
<div class="mb-3">
<label for="postcontent">Post</label>
<textarea class="form-control text-area" id="postcontent" name="content" rows="4" cols="50" required
placeholder="Start writing your blog ..............."><%=post.content%></textarea>
</div>
<button class="btn btn-primary publish-btn" type="submit" name="button">Update</button>
</form>
If this answers your question mark it as done

Cannot POST /admin Error return in web browser

I want to update my images on the blog page. but I got an error in the web browser like
Cannot POST /admin/portfolio/609911b1fba77be609396747/edit_cover
here is edit_cover.ejs file code and I use post method to submit images in the database
<%-include('./partials/header')%>
<div class="container-fluid">
<h1 class="text text-primary">Change Porfolio Cover Image Section</h1>
<div class="card shadow mb-4">
<div class="card-header">
<form action="/admin/portfolio/<%=work._id%>/edit_cover" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="exampleFormControlFile1">Cover</label>
<input type="file" name="cover" class="form-control-file" id="exampleFormControlFile1">
</div>
<div class="form-group">
<label for="exampleFormControlFile2">Snaps of Project</label>
<input class="form-control-file" name="images" type="file" id="exampleFormControlFile2" multiple>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success" >Update</button>
</div>
</form>
</div>
<div class="card-body">
<div class="table-responsive">
</div>
</div>
</div>
My router.js file code is here and two lines of code in here one is get request and other is for post
router.get('/admin/portfolio/:id/cover_edit',serverController.isAuthenticated,serverController.portfolio_edit_cover)
router.post('/admin/portfolio/:id/cover_edit',serverController.isAuthenticated,upload.fields([{name: "cover", maxCount: 1},{name: "images", maxCount: 12}]),serverController.portfolio_edit_cover_post)
here is my backend controller and code for images updating
exports.portfolio_edit_cover = async function(req,res){
res.render('server/edit_cover',{
work : await workCollection.findOne({_id: objectId(req.params.id)})
})
}
exports.portfolio_edit_cover_post = function(req,res){
let uploadImages = new Work(req.body, req.files, req.params.id)
console.log(req.files)
uploadImages.up().then((result)=>{
res.redirect('/admin/portfolio',{
work : result
})
}).catch(()=>{
res.send('404')
})
}
and lastly this all about my model codes. in the following code is just for how update my data onto databae
Work.prototype.up = function(){
return new Promise(async(resolve,reject)=>{
await workCollection.updateOne({_id : objectId(this.id)}, {$set :
{
images : this.images
}
}
)
resolve()
})
}
module.exports = Work
in edit_cover.js file it has path like
action="/admin/portfolio/<%=work._id%>**/edit_cover**" and router.js it's like
router.get('/admin/portfolio/:id**/cover_edit**',serverController.isAuthenticated,serverController.portfolio_edit_cover)
router.post('/admin/portfolio/:id**/cover_edit**',serverController.isAuthenticated,upload.fields([{name: "cover", maxCount: 1},{name: "images", maxCount: 12}]),serverController.portfolio_edit_cover_post)
both of these need to have the same path; everything is fine but at last segment, it should be /cover_edit

Submitting a form results to a url segment undefined in NodeJs

I am setting up a simple form submission, when I submit the form the url becomes undefined
This is the view: http://localhost:3000/dashboard/tours/categories
router.get('/tours/categories', function (req, res) {
res.render('agents/tourcategories', {
page_link: 'wishlist'
});
});
This is the form:
<form method="POST" action="/dashboard/tours/categories" >
<div class="box_general padding_bottom">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Category Name</label>
<input type="text" name="categoryname" class="form-control" placeholder="e.g Hiking">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-secondary pull-left" type="button" data-
dismiss="modal">Cancel</button>
<button id="" type="submit" class="btn btn-primary" >Save</a>
</div>
</form>
when I submit the form tne url changes to: `
http://localhost:3000/dashboard/tours/undefined
router.post('/tours/categories',function (req, res) {
console.log("We are here");
const category = new CategoriesDB({
categoryname: req.body.categoryname,
addedby: res.locals.useremail
});
// Save a Customer in the MongoDB
CategoriesDB.save(function (err) {
if(err){
console.log(err);
return;
}else{
res.redirect('/tours/categories');
}
})
});
I realy dont know where the undefined came from, I have checked everything seems to be okay. It keeps popping up in the url everythime i submit the form
`
From the snippets of the code you have posted, It might be because u have not used the middleware
router.all("/dashboard*");
But if u have used that and the GET request is working but not the POST then u will need to post more snippets of your code, mainly the middleware you defined to handle the routes

How to use endpoint inside another endpoint in express node js

I am just stuck in a problem and also don't know whether the question is correct or not.
I am working on a node express js, using ejs templating engine.
I have created certain endpoints (say login(POST) endpoint) which are generic endpoints.
Now I want to create a new application which uses should use these endpoints and render the view according to the result of these endpoints.
Lets say I have a generic endpoint for login
router.post('/user/login', function (req, res) {
var userLoginId = req.body.username;
var currentPassword = req.body.password;
UserLogin.findOne({userLoginId: userLoginId, currentPassword: currentPassword}, function (err, usr) {
if (err) {
console.log('Error in User login');
console.log(err);
res.status(500).type('application/problem+json').send();
} else {
if (!usr) {
console.log('Please enter valid username and password');
res.status(404).type('application/problem+json').send();
} else {
res.type('application/json').status(200).send(usr);
}
}
});
});
And I am using this login.ejs file
<div class="container panel panel-primary">
<h2 class="h2 text-center">Login</h2>
<form class="form-horizontal" name="loginForm" method="post" action="/user/login">
<div class="form-group">
<label for="username" class="col-sm-offset-2 col-sm-2 control-label">UserName</label>
<div class="col-sm-4">
<input type="text" name="username" class="form-control" id="username" placeholder="username">
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-offset-2 col-sm-2 control-label">Password</label>
<div class="col-sm-4">
<input type="password" name="password" class="form-control" id="password" placeholder="Password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-4">
<button type="submit" class="btn btn-primary btn-">Sign in</button>
</div>
</div>
</form>
</div>
Now I want to use this code and want to login to the system.
If the user login is successful I want to redirect to dashboard page else same login page.
On executing this code the api returns me the JSON response and from this response how can I decide to whether to redirect on dashboard page or login page.
Please help if more input is needed please put a comment.
I would instead of doing a form request to login, do a AJAX request to login and then use something like jQuery to do the AJAX request and response. Alternatively you could do something like the following.
router.get('/login', function(req, res){
res.render('login', {});
})
router.post('/login', function (req, res) {
var userLoginId = req.body.username;
var currentPassword = req.body.password;
UserLogin.findOne({userLoginId: userLoginId, currentPassword: currentPassword}, function (err, usr) {
if (err) {
console.log('Error in User login');
console.log(err);
// res.status(500).type('application/problem+json').send();
res.status(500).render('login', { error : 'Error finding password'})
} else {
if (!usr) {
console.log('Please enter valid username and password');
// res.status(404).type('application/problem+json').send();
res.status(404).render('login', { error : 'Please enter valid username and password'})
} else {
res.redirect('/dashboard');
}
}
});
});
For the login.ejs file i would conditionally render the error.
<!DOCTYPE html>
<html>
<body>
<div class="container panel panel-primary">
<h2 class="h2 text-center">Login</h2>
<%if (locals.error) { %>
<%= error %>
<% } %>
<form class="form-horizontal" name="loginForm" method="post" action="/user/login">
<div class="form-group">
<label for="username" class="col-sm-offset-2 col-sm-2 control-label">UserName</label>
<div class="col-sm-4">
<input type="text" name="username" class="form-control" id="username" placeholder="username">
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-offset-2 col-sm-2 control-label">Password</label>
<div class="col-sm-4">
<input type="password" name="password" class="form-control" id="password" placeholder="Password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-4">
<button type="submit" class="btn btn-primary btn-">Sign in</button>
</div>
</div>
</form>
</div>
</body>
</html>

Logic doesn't work after .then

I have a Login end point that respond me a json.
I'm using vue-router to do a POST and then Store a token in localStorage, but after the POST, the json shows on the screen:
{"success":false,"message":"Login ou senha inválidos!"}
It should return on the page login, with the message
This is the code:
var vmLogin = new Vue({
el: '#login',
data: {
email: '',
msg: '',
password: ''
},
beforeCreate: function () {
if(localStorage.getItem("timeTaskToken") !== null) {
window.location.href = '/'
}
},
methods: {
getLogin: function (e) {
this.$http.post('/login', {email: this.email, password: this.password}).then((response) => {
alert('teste!');
if(response.body.success === true) {
localStorage.setItem("timeTaskToken", response.body.token);
window.location.href = '/'
} else {
this.msg = response.body.message
}
}, (response) => {
// error callback
});
e.preventDefault();
}
}
});
login page
<form id="login" class="form-horizontal" method="post">
<h3>{{ msg }}</h3>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="email" v-model="email" class="form-control" name="email" placeholder="Email">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">Password</label>
<div class="col-sm-10">
<input type="password" v-model="password" class="form-control" name="password" placeholder="Password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<div class="checkbox">
<label>
<input type="checkbox"> Remember me
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default" #click="getLogin">Sign
in</button>
</div>
</div>
</form>
It's like nothing after .then works...
The returned JSON just appear in the screen.
I expect the problem is that the Sign In button is a submit button and you just want it to be a button button.
Change
<button type="submit" class="btn btn-default" #click="getLogin">Sign in</button>
To
<button type="button" class="btn btn-default" #click="getLogin">Sign in</button>
Note the type="button".
If you leave it as type submit then the form is is actually posted and code execution will stop. This also explains why you see a page that has just the JSON result; that is just the response from posting that form.
Alternatively, move e.preventDefault() to the top of the method.
You could also use #click.prevent="getLogin".
Just add a console.error in you error callback
}, (response) => {
console.error(response);
});
This is the first step because maybe you just enter here ..

Resources