Angularjs make post request to server with key value pair - angularjs

I am so beginner programming with Angularjs and I want to make post request to my server. On the server side I'am waiting data with key value pair. But when I try to post with the example code below I sent data in json so ı can't parse it on the server side. I googled this issue but i couldn't find the answer but I'm pretty sure there is a way. I hope somebody will tell this.
$scope.postData = function postData(data) {
$http.post('apiurl/functionName', {post_data:data}).success(
alert("Success"));
};

var request = {};
request.method = 'POST';
request.data = JSON.stringify(JSONdata);
request.url = url;
request.timeout = 1000 * 60;
var promise = $http(request);
promise.success(function(data, status, header, config) {
// successCallback;
});
promise.error(function(data, status, header, config) {
// errorCallback
});

Related

Restangular GET request returns 100 records only

I am using a Restangular library in my angularjs application.I want to retrieve all registered user's information from rest api.Whenever I make Restangular GET request to do so it retrieves only 100 records while I have around 250+ users for my website.I've tried using
Restangular.all('url').getList({limit:200,offset:0})
.then(function (success) {
//some code
});
This was the wayout mentioned here but it isn't working for me.
Found solution after some time
RestFullResponse.all('url').getList().then(function (success) {
var headers = success.headers();
var currentpage = headers['x-pager-current-page'];
var lastpage = headers['x-pager-last-page'];
for(currentpage; currentpage<=lastpage; currentpage++) {
var param = {
"page_entries": 100,
"page":currentpage,
"offset": (currentpage-1)*this.page_entries
};
RestFullResponse.all('url').getList(param).then(function (success) {
personList = personList.concat(success['data']);
});
}
});

How to save and set headers on each request with Angular Interceptors

I'm trying to setup token auth but can't seem to figure out a good way to save the headers the server is sending me into a cookie. I then need to read that value out of the cookie and into the new request headers.
I'm using Angular 1.5
Here's some simple code I've been trying to work with:
os.config(['$httpProvider', function ($httpProvider) {
return {
'request': function(config) {
var access_token = $cookies.get('access-token');
var token_type = $cookies.get('token-type');
var client = $cookies.get('client');
var uid = $cookies.get('uid');
$httpProvider.defaults.headers.post['access-token'] = access_token;
$httpProvider.defaults.headers.post['token-type'] = token_type;
$httpProvider.defaults.headers.post['client'] = client;
$httpProvider.defaults.headers.post['uid'] = uid;
},
'response': function(response) {
$cookies.put('access-token', 'oatmeal');
$cookies.put('token-type', 'oatmeal');
$cookies.put('client', 'oatmeal');
$cookies.put('uid', 'oatmeal');
}
};
}]);
EDIT: People have been commenting trying to show me how to set headers. I can do that easily, as you can see in the example. What I need to do is save the response headers after I've made a request. These need to be saved into a cookie which is what my question pertains to.
I'm interested in a method that doesn't require me to run some function in the .then part of every single API request I do, that's not DRY and seems like madness...

Working with HTTP POST request with AngularJS

I'm developing a jsp which sends POST requests to a servlet. I would like to write content in raw payload instead of key-value form.
var addItemApp = angular.module('addItem',[]);
addItemApp.controller('addItemCtrl', function($scope, $http){
$scope.addItemBnClicked = function(){
var rqst = $http.post('http://127.0.0.1:8180/JSP/ws', "This is a test content");
rqst.success(function(rspnData, status, headers, config){
alert("Status: " + status);
});
}
});
Checking on the server side, I found that the payload doesn't contain anything. Please help, Thanks. ^^
%%%%%%%%%%%%%%% Edit %%%%%%%%%%%%%%%
I use the following code to get the payload.
String line = "";
String rqstRawBody = "";
while((line = servletRqst.getReader().readLine()) != null){
rqstRawBody += line;
}
System.out.println("rqstRawBody: " + rqstRawBody);
The rqstRawBody is finally an empty string. I believe the above java code is okay, as I get raw payload correctly for those requests sent using the chrome-app Rest Client.
You should change the Content-Type HTTP header. By default Angular sets that to application/json for a POST request.
var config = { headers: { 'Content-Type': 'text/plain' } };
var data = { someKey: 'SomeValue'};
$http.post('/url', data, config).then(...);
Or you can set it as the default for all requests as shown in the documentation:
module.run(function($http) {
$http.defaults.headers.common['Content-Type']= 'text/plain'
});

angular js post request to nodejs json. key undefined express 4

https://codeforgeek.com/2014/07/angular-post-request-php/
Hi I was following the above link to give post request from angular js to node js. I received the data posted in below format when i give
console.log(req.body);
{ '{"email":"test#test.com","pass":"password"}': '' }
and when i try to get the value as below, it says undefined.
var email = req.body.email;
console.log(email);
I am unable to get the value of email and pass. Thank you
change the client side header code to headers: { 'Content-Type': 'application/json' }
Your Angular code is sending JSON data, but your Express app is parsing it as URL encoded data.
You probably have something like this in your Express app:
var bodyParser = require('body-parser');
...
app.use(bodyParser.urlencoded());
That last line should be:
app.use(bodyParser.json());
You did not well explain the problem , please next time try to post a bigger part of your code so we could understand what you wanted to do / to say .
To answer your question i will copy/paste a part of my code that enable you to receive a post request from your frontend application(angularJS) to your backend application (NodeJS), and another function that enable you to do the inverse send a post request from nodeJS to another application (that might consume it):
1) receive a request send from angularJS or whatever inside your nodeJS app
//Import the necessary libraries/declare the necessary objects
var express = require("express");
var myParser = require("body-parser");
var app = express();
// we will need the following imports for the inverse operation
var https = require('https')
var querystring = require('querystring')
// we need these variables for the post request:
var Vorname ;
var Name ;
var e_mail ;
var Strasse ;
app.use(myParser.urlencoded({extended : true}));
// the post request is send from http://localhost:8080/yourpath
app.post("/yourpath", function(request, response ) {
// test the post request
if (!request.body) return res.sendStatus(400);
// fill the variables with the user data
Vorname =request.body.Vorname;
Name =request.body.Name;
e_mail =request.body.e_mail;
Strasse =request.body.Strasse;
response.status(200).send(request.body.title);
});
2) Do the inverse send a POST request from a nodeJS application to another application
function sendPostRequest()
{
// prepare the data that we are going to send to anymotion
var jsonData = querystring.stringify({
"Land": "Land",
"Vorname": "Vorname",
"Name": "Name",
"Strasse": Strasse,
});
var post_options = {
host: 'achref.gassoumi.de',
port: '443',
method: 'POST',
path: '/api/mAPI',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': jsonData.length
}
};
// request object
var post_req = https.request(post_options, function(res) {
var result = '';
res.on('data', function (chunk) {
result += chunk;
console.log(result);
});
res.on('end', function () {
// show the result in the console : the thrown result in response of our post request
console.log(result);
});
res.on('error', function (err) {
// show possible error while receiving the result of our post request
console.log(err);
})
});
post_req.on('error', function (err) {
// show error if the post request is not succeed
console.log(err);
});
// post the data
post_req.write(jsonData);
post_req.end();
// ps : I used a https post request , you could use http if you want but you have to change the imported library and some stuffs in the code
}
So finally , I hope this answer will helps anyone who is looking on how to get a post request in node JS and how to send a Post request from nodeJS application.
For further details about how to receive a post request please read the npm documentation for body-parser library : npm official website documentation
I hope you enjoyed this and Viel spaß(have fun in german language).

How to pass multiple parameters in a URL Angular/REST API

I'm trying to pass multiple parameters in a URL with no luck. I'm not sure if it makes a difference but I am doing it through Angular. I'm trying to send the request to a REST API backend that I know works for single requests. Here is what my backend looks like
index.js
var express = require('express');
var router = express.Router();
var game = require('./game');
router.get('/api/v1/gameRefined/:from_datepicker:to_datepicker:from_timepicker:to_timepicker:selectLevel', game.getAllRefined);
module.exports = router;
game.js
...dbconnection stuff...
var game={
getAllRefined: function(req, res) {
var refines = req.params;
console.log("getting refined games");
pool.getConnection(function(err, connection){
var query = connection.query('SELECT * FROM game WHERE date >= ? AND date <= ? AND time >= ? AND time <= ? and level = ?', [refines.from_datepicker, refines.to_datepicker, refines.from_timepicker, refines.to_timepicker, refines.selectLevel], function(err, rows) {
connection.release();
if(err) {
throw err;
}else{
res.json(rows);
}
});
})
},
}
module.exports = game;
I send the request from this factory
.factory('gameFactory', ['$http',
function($http) {
var _gameFactory = {};
_gameFactory.getRefinedGames = function(dateFrom,dateTo,timeFrom,timeTo,level) {
var encodedParam = encodeURIComponent(baseUrl + '/api/v1/gameRefined/?from_datepicker='+dateFrom+'&to_datepicker='+dateTo+'&from_timepicker='+timeFrom+'&to_timepicker='+timeTo+'&selectLevel='+level+'');
return $http.get(encodedParam);
}
return _gameFactory;
}])
That sends this request that comes back as a 404:
http://localhost:8100/http%3A%2F%2Flocalhost%3A3000%2Fapi%2Fv1%2FgameRefined%2F%3Ffrom_datepicker%3D2015-02-05%26to_datepicker%3D2015-02-19%26from_timepicker%3D12%3A00%26to_timepicker%3D18%3A00%26selectLevel%3D1
I have tried it encoded and not encoded, with forward slashs, with semi colons, but nothing has worked so far.
I don't know why a localhost gets appended at the start, but even trying it in postman without the first localhost still is a 404 error.
How should I be doing this? Any help is appreciated. Thank you.
First, other than separating the work into a factory, you aren't really using Angular here. Second, I would consider posting to your API, return JSON results from the API, and then use a promise to read the data back into Angular.
Use $http.post
Let Angular do this work for you. Something like the below will generate the URL request for you. The return value of $http is also a promise, so using .success and .error will allow you to parse any returned data as well, even if it is just a success or failure message - but it is a great method of passing data between server/API and client.
.factory('gameFactory', ['$http',
function($http) {
return {
reachAPI: function(dateFrom, dateTo) {
$http.post('http://localhost:8080/api/v1', {
'dateFrom': dateFrom,
'dateTo': dateTo
})
.success(function(data, status, headers, config) {
*things happen*
data.somethingReturned // from your API
});
}
}]);
Consider body-parser
I know you said you have confidence in your REST API structure, but body-parser is an Express middleware that can parse URL-encoded strings and may prove helpful in reading your data. Personally, I think it lends towards more readable code.
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
router.route('/api').post(function(req, res) {
*things happen*
req.body.dateFrom //find your data
*things happen*
res.json(returnedData);
});
Hope that helps

Resources