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

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".

Related

Using javascript code in express-handlebars

I am using nodejs server to run my app along with express-handlebars engine as view engine . I wonder how can I use javascript code in the view in order to manipulate data given by the server as illustrated below :
// from server
app.get("/newcalendar", (req, res)=>{
rdv.find().
then(data=>{
res.render("newcalendar", {servData:data});
})
.catch(error=>{
return console.log(error)
})
});
// to view : newcalendar.hbs , I want to use javascript to manipulate the recieved data :servData
<div>
{{#each servData}}
{{this}} // how can I manupulate this using javascript ?
{{/each}}
</div>

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!!!!!');
});

Disable CORS in ExpressJS

I have two nodeJS/express applications. For simplicity, I'll say one is hosted on www.example1.com and the other is hosted on www.example2.com. I want to send a POST request from www.example2.com to wwww.example1.com. I do this with the following code:
<form action="www.example1.com" method="POST">
<input type="text" name="name"></input>
<input type="submit" value="Submit"></input>
</form>
I only want this to accept requests from www.example1.com. How do I do this? Also, currently, when I do this post request, the POST request is actually going through. I don't understand why. Are there no default settings to prevent against the cross domain requests? How can I put up these settings.
Any help would be greatly appreciated!
Thanks!
the cors middleware package is the standard way to do this
https://www.npmjs.com/package/cors
e.g:
const allowedOrigins = ['www.example1.com',
'www.example2.com'];
app.use(cors({
origin: function(origin, callback){
if(!origin) return callback(null, true);
if(allowedOrigins.indexOf(origin) === -1){
const msg = 'The CORS policy for this site does not allow access from the specified Origin.';
return callback(new Error(msg), false);
}
return callback(null, true);
}
}));

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?

How can i access a nodeJS variable in ejs views in a sails project?

My LoginController.js looks like this:
module.exports = {
getAuthorizationLink: function (req, res) {
res.send({
authorization_link: sails.config.FACEBOOK_LOGIN_URL
})
}
}
I need to redirect to the authorization_link when a button is clicked
<div class="col-md-4 text-center">
<button id="authenticate" class="btn btn-primary">Authenticate Page</button>
<script type="text/javascript">
document.getElementById("authenticate").onclick = function () {
...
};
</script>
</div>
Here you are looking to mix server-side (EJS) & client-side JS code.
It is possible, makes sense to do sometimes but it is not clean.
Once you understand you are doing this. Variable can be passed and accessed.
Using EJS, write JS code for client side e.g.
var auth_link = '<%= authorization_link %>';
this line will become something like below for client-side JS
var auth_link = 'https://fb.com/login';
Now you can use auth_link in client-side JS as required
Also, check res.view for responding with HTML page

Resources