Working with HTTP POST request with AngularJS - 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'
});

Related

$http.post in angularjs not work to me and $http.get has response errors

I am new to angularjs am tying to learn it but some problems faced me, actually they are two problems:
First Problem: $http.post never works as there is no action and there is no response. However, $http.get is able to work.
Second Problem: Because of the first problem I call my restful webservice by $http.get, but the web service response status always is -1. Though the web service is able to do its work successfully and always response data null, can any one help me.
this my angular part:
var app = angular.module('myLogin',[]);
app.controller('loginController',function($scope,$http){
$scope.login=function(){
var username = $scope.username;
var password = $scope.pass;
$http.get("http://localhost:8080/spring/webservice/login/"+username+"/"+password)
.success(function(data,status){
alert("data : "+data);
alert("Data Inserted Successfully");
window.location.href = "chatScreen.html";
})
.error(function(data,status){
alert("Status: "+status);
window.location.href = "login.html";
});
}
});
and this my web service:
/**
* web service part
*/
#RequestMapping(value="webservice/login/{name}/{pass}", method=RequestMethod.GET)
#ResponseStatus(value = HttpStatus.OK)
public ResponseEntity<String> weblogin(#PathVariable("name") String name, #PathVariable("pass") String pass)
{
System.out.print("username : "+name);
System.out.print(pass);
UserService service = new UserService();
List<UserBean> users = service.getUsers();
if(users!=null)
{
for(UserBean user : users)
if( ( user.getUsername().equals(name) ) && ( user.getPassword().equals(pass) ) )
{
System.out.print("success");
username = name;
//model.addAttribute("result", "Welcome to chat..");
MessageService messageService = new MessageService();
List<MessageBean> messages = messageService.getMessage(username);
String userMessages="";
if(messages != null)
{
for(MessageBean msg : messages)
userMessages +="\n"+msg.getSender() + ": " + msg.getMessage()+" \n";
}
else
userMessages +="You have no Messages !";
//model.addAttribute("whoSendToMe", userMessages);
return new ResponseEntity(HttpStatus.OK);
}
}
return new ResponseEntity<String>("faild", HttpStatus.NOT_FOUND);
}
refer this may be this will give you idea how to approach your problem:-
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this is asynchronous call back
// you will get your data here comming from rest
}, function errorCallback(response) {
// called asynchronously if an error occurs
});
share your code so we will try to solve it
If you use method GET and you receive a -1 returned, it means normally that you are giving a wrong URL.
As for then POST method you should use this syntax:
return $http({
method: 'POST',
url: 'index.php/email/createDeliverable',
data: $.param({
csrfTokenName: --your token--,
userName: user.name,
password: password
}),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
Remember to add the headers part.
Your server may need a CSRF token validation, in this case you need to pass it, see un my example: csrfTokenName: --your token--,

AngularJs POST request for json not working

Hi i tried POST json data in two ways its response in null
var jsonData = $scope.addedCat;
console.log(jsonData);
var request = $http({
method:"POST",
url:base_url+"Category_controller/json_test",
data: JSON.stringify(jsonData),
dataType: "application/json"
});
request.success(
function(response){
console.log(response);
});
var cat_j = $scope.addedCat;
var data = $.param({ json:JSON.stringify(cat_j)});
$http.post(base_url+"Category_controller/json_test/",data).success(function(data, status) {
console.log(data);
console.log(status);
})
How we decode the json data in php.
I tried like this in Codeignitor framework.
$cjson = $this->input->post('jsonData');
$cat_json = json_decode($cjson);
echo json_encode($cat_json);
On your server php file , try that instead, and you get the parametes passed from client:
//get parameters
$params = json_decode(file_get_contents('php://input'), true); //read values from angular directive
Superglobal $_post only support application/x-www-form-urlencoded and multipart/form-data-encoded.
For application/json you should use php://input which can give you the raw bytes of the data. Here is a sample code of how to get the input data:
// get the raw POST data
$rawData = file_get_contents("php://input");
// this returns null if not valid json
print_r(json_decode($rawData));
$data = json_decode(file_get_contents('php://input'), true);
and do $data['jsonData']
now this $data['jsonData'] === $this->input->post('jsonData');

Angular JS return undefined response

I am trying to make a http request and get the results which
I am able to do in the browser with the following
http://dev.markitondemand.com/MODApis/Api/v2/InteractiveChart/json?parameters={"Normalized":false,"NumberOfDays":5,"DataPeriod":"Day","Elements":[{"Symbol":"ACN","Type":"price","Params":["c"]}]}
But when I execute the following code the response returned is undefined.Can you tell me what am I doing wrong here
var test = JSON.stringify({"Normalized":false,
"NumberOfDays":5,
"DataPeriod":"Day",
"Elements":[{"Symbol":"ACN",
"Type":"price",
"Params":["c"]
}]
});
console.log(test);
$http({
url:"http://dev.markitondemand.com/MODApis/Api/v2/InteractiveChart/json",
method : "GET",
parameters: test
}).then(
/* success */
function(response) {
var stock = {};
stock = angular.fromJson(response);
var Data = stock.Dates;
console.log(Data);
$scope.content = response.data;
$scope.statuscode = response.status;
$scope.statustext = response.statustext;
console.log('success');
},
/* failure */
function(result) {
console.log('error');
});
Please guide me
Your Content-Type in response header is not properly set.
Check whether Content-Type in response header is application/json or not.
Currently it look like this Content-Type:text/javascript; charset=UTF-8
So, your response is not recieved in JSON format.Check for proper JSON encoding

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

Angularjs make post request to server with key value pair

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

Resources