Send ejs field to a nodejs file - node.js

I have the following ejs code.
<form action="/" class = "form-horizontal" method="post">
<textarea class = 'form-control departureCode' name = "departureCode" rows= "1"></textarea>
</form>
This is my post handler code in routes.js file.
routes.post('/', (req, res, next) => {
let departureCode = JSON.parse(req.body.departureCode);
console.log(departureCode);
});
I m not getting this to work successfully. I am getting undefined token error inside my post handler. Could you please help me?

removed JSON.Parse from
let departureCode = JSON.parse(req.body.departureCode);
It worked. Also, made changes suggested by Yogesh Patel in the comments. Thank you all.

Related

Cannot POST /addfriend error using Express

I am trying to create a simple form handler using express. Here is a similar question but I can't related it with my problem. I have written all of my file Here anyone can check it by using all of my file. For better understanding I copy my code here:
app.js code:
const express = require('express');
const app = express();
//routes
app.get('/',function(req,res){
res.send('This is root dir');
});
app.get('/friends',function(req,res){
var friends=['sakib','emon','rayhan'];
res.render('friends.ejs',{friends:friends});
});
app.get('/addfriend',function(req,res){
res.send('ADD friend page launch!!!!!');
});
app.listen(3000,function(){
console.log("server has started on port 3000!!!");
});
ejs(friends.ejs) code:
<h1>Here is list of your Friend:</h1>
<%friends.forEach(function(friend){%>
<li><%=friend%></li>
<%});%>
<form action="/addfriend" method="POST">
<input type="text" name="friend" placeholder="name">
<button>
Submit
</button>
</form>
When I type any name in the input box and clicked Submit it didn't post to /addfriend. I didn't understand where is my problem. Please goto input box(link) after started the server.
For better understand what's my actual problem is then please use goorm IDE(shared file) where I uploaded everything.
You are using get request instead of post for addfriend.
app.post('/addfriend',function(req,res){
console.log("I'm called wohoo!");
res.send('ADD friend page launch!!!!!');
});

Angular 5 - FileUpload not working

Edit: Fixed. I had to add this to my response:
.subscribe(data =>{
console.log('data is here: ', data);
});
I have read through whole bunch of articles on this one, but cannot get it to working.
Environment: Angular 5, NodeJS backend with Express. Using Express-FileUpload to upload the file.
I tried my API with this simple HTML:
<html>
<body>
<form ref='uploadForm'
id='uploadForm'
action='http://192.168.1.20:8275/api/upload'
method='post'
encType="multipart/form-data">
<input type="file" name="sampleFile" />
<input type='submit' value='Upload!' />
</form>
</body>
</html>
Figured that my API is working fine, the API End point receives the request from HTML just fine. Now, this is what I am trying to do Angular:
let body = new FormData();
body.append("file", file, 'thefilename');
let options: RequestOptions = new RequestOptions();
options.headers = new Headers();
let response: Observable<Response> = this.http.post('http://192.168.1.20:8275/api/upload', body, options); //code just breaks here and exists silently
response.map(json =>{
console.log('gotcha')
}),err =>{
console.log('error: ', err);
};
Angular code doesn't work. After the POST call, it breaks and exits silently. Nothing in console, no error. And I am unable to figure out why? I read through articles, and found we don't have to supply a content type to make it work. I tried that too but no luck. What can be the issue?

what is use of router and model in loopback

hello guys i m new to loopback so can anyone help me with this basic. i had created a some code but don't know how this flow (from route to model)
here is route.js code for login
var path = require('path');
module.exports = function(app) {
app.get('/', function(req, res) {
res.render('login');
});
app.post('/login', function(req, res) {
//from here i should go to login model
});
};
here is my login.ejs
<form action="/login" method="post">
<input type="text" name="username" placeholder="username">
<input type="password" name="password" placeholder="password">
<input type="submit" name="" value="Submit">
</form>
now my question is that how i can use login model from route.js (url is like "login") i know i can use this type as describe below in route.js but i want that first it go to router and from then i go to login model more description eg it go through "/login" route from there it go to login model where i want to add insert login after that if it response success then it go to "/home" else it go to "/"
"var User = app.models.user;"
i what something like this in user.js (model)
module.exports = function(User) {
//here i want to accept login form method and insert it into dataabase
};
or this is not possible or it is incorrect way i don't know much so please help
what is different between if i use business login in router and model i m new so please help.
First go to the loopBack documentation and read it carefully how to create models and its control flow , surely you will get clear picture
https://loopback.io/doc/en/lb2/Project-layout-reference.html

Req.file object is always undefined, HTTP file upload

I'm trying to upload a file in meteor using HTTP POST method and enctype="multipart/form-data"
WebApp.connectHandlers.use("/api/v1/upload", function(req, res, next) {
console.log(req.files); //undefined
console.log(req.file); //undefined
console.log(req);
})
I tried with WebApp but getting undefined file property under request object
I also tried with multer and Picker but no luck.
const _multerInstanceConfig = { dest: '/tmp' }; // Temp dir for multer
const _multerInstance = multer(_multerInstanceConfig);
Picker.middleware(_multerInstance.single('photo'));
Picker.route('/api/v1/upload', function(params, req, res, next) {
console.log(req.files); //undefined
console.log(req.file); //undefined
console.log(req);
})
This is simplest form I'm trying to upload is
<form action="http://localhost:3000/api/v1/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="Upload File" />
</form>
Am I missing something here? not sure.
Also, I don't want to upload files using base64 data string via DDP as it very slow.
I've check couple of link also with no luck
multer - req.file always undefined
https://github.com/noris666/Meteor-Files-POST-Example
PS: I need to upload images via native Android/iOS clients.
Thanks, everyone, who has spent their time on my question, I got the solution for the problem from git issue, I raised.
I'm posting here my solution if someone else also faces the similar problem.
It was because of the name of this input field
<input type="file" name="file" />
which doesn't match with
Picker.middleware(_multerInstance.single('photo'));
changing either of them to will make it work perfectly.

Get ng-model values on POST to Express.js endpoint

I am creating a Node.js application with AngularJS.
I want to make a simple POST, using Angular. This POST should post a couple of values to my server, where I can see them using console.log.
In my HTML code, I build it with the ng-model and a button that has a ng-click.
I can tell my Node.js server is being hit, as it outputs the post called in the console.
However, I have been trying to read about how to read the POST values, but I haven't found a solution.
How would I modify my code to read serialKey and gameTitle in my Express.js endpoint?
My HTML code:
<div class="input-group" ng-controller="CreateController">
<p>Serial key:<br/>
<input class="form-control" ng-model="serialKey" />
</p>
<p>Game:<br/>
<input class="form-control" ng-model="gameTitle" />
</p>
<span class="input-group-btn">
<button class="btn btn-default"
ng-click="postNewIsbn(serialKey,gameTitle)">Add</button>
</span>
</div>
Angular controller code:
app.controller('CreateController',function($scope, $http) {
var url = '/api/serials';
$scope.postNewIsbn = function(serial, game) {
$http.post(url, {
serial: serial,
gametitle: game
})
.success(function (data) {
$scope.data.status = 'success';
})
.error(function(error) {
$scope.data.error = error;
});
};
});
Express.js endpoint
app.post('/api/serials',function(req,res){
console.log(req.body);
console.log('post called');
});
It appears to be the problem of setting content-type header. In your angular application you can set defaultHeaders for your post request just after you initialize the module or in your config function with this line
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
Do remember to inject the $httpProvider dependency whereever you setting this header
UPDATE
It may be the case that you need to configure your express in order to use the bodyParser with this line:
app.use(express.bodyParser());
req.param(name)
When attempting to retrieve data passed with the request, the req.param() function checks the following in order to find the parameter:
req.params
req.body
req.query
See the docs here.
Also, try explicitly setting the content-type header in the POST request to "application/json".

Resources