I am new to angularjs. I am trying to post a request from angularjs to spring controller. The request object is logged properly in angular but it reaches as null in controller.
I have been through the similar questions but they didn't worked out for me :
getting null using angular post
angularjs-spring-mvc-json-post-request
spring-angularjs-receiving-null-data-on-server
Controller.js :
$scope.addExpense = function (expense) {
console.log("Received"+expense.amount+expense.description);
var expenseDetail = {
description:expense.description,
amount:expense.amount,
created:'',
updated:'',
};
console.log("expense detail : "+JSON.stringify(expenseDetail));
$http({
method : 'POST',
dataType: 'json',
url : 'addExpense1',
data : JSON.stringify(expenseDetail),
headers: {
"Content-Type": "application/json"
}
}).success(function (response) {
console.log(response.data);
}).error(function(response){
console.log("Error : "+response.data);
});
};
Controller method :
#RequestMapping(value = "addExpense1", method = RequestMethod.POST)
#ResponseBody
public List<ExpenseDetail> addExpense1(#RequestBody ExpenseDetailDTO expenseDetailDTO) {
LOG.info("Request to add description : " + expenseDetailDTO.getDescription());
if(expenseDetailDTO==null || expenseDetailDTO.getDescription()==null || expenseDetailDTO.getAmount()==null)
return null;
expenseService.addExpense(expenseDetailDTO);
List<ExpenseDetail> expenseDetails = expenseService.getAllForToday();
LOG.info("Expense Details fetched : " + expenseDetails.size());
return expenseDetails;
}
On controller following log is printed :
Request to add description : null
I am not getting error anywhere.
Kindly help me out.
i had similar issue in the past using spring webmvc.
https://github.com/sombriks/rango-vote-spring/blob/master/src/main/java/rango/vote/RangoVoteController.java
What solved in my case was the addition of jackson-databind dependency and the proper configuration:
https://github.com/sombriks/rango-vote-spring/blob/master/build.gradle#L54
https://github.com/sombriks/rango-vote-spring/blob/master/src/main/webapp/WEB-INF/applicationContext.xml#L29
If possible, prefer spring + jersey over spring webmvc since you could use jaxb to properly map your data objects:
http://pastebin.com/TVsrJJm7
http://pastebin.com/jE7z1u3k
http://pastebin.com/39QDBgQD
Hope it helps
Related
I am very new to angularJS.
My Backend is DRF and I have successfully implemented token.
this is my token:
{
"key": "217c3b5913b583a0dc3285e3521c58b4d7d88ce2"
}
Before I implement token in backend, it was working nice:
$scope.getAllContact = function() {
var data = $http.get("http://127.0.0.1:8000/api/v1/contact")
.then(function(response) {
$scope.contacts = response.data;
});
};
But, now I am not getting how can I implement this token here
Can anyone help me in this case?
Try to use this. You need to attach the token in the headers.
$http({
url : "http://127.0.0.1:8000/api/v1/contact",
method : 'GET',
headers : {
'Content-Type' : 'application/json',
'key': "217c3b5913b583a0dc3285e3521c58b4d7d88ce2"
}
}).then(function(response){
$scope.contacts = response.data;
});
Note that, this is binding the token to only this request. Use $http interceptors to add the token to each request that you make.
See here: Angular Js - set token on header default
I am trying to pass data as JSON object by $http.Post to webAPI method. In WebAPI method, the parameter of the method is a class object.
It works fine when I test the webAPI method by Postman.But I am not able to pass the JSON object by angular $http.post method-I get null values in the webAPI parameter(in the class object).
Can someone please advise how to fix the issue.i am new to AngularJS.Kindly help.
AngularJS Code
angular.module('Test.Employer')
.controller('EmployerController', ['$scope','headerValue', '$http',
function ($scope, headerValue, $http) {
var ipEmployerDetls = {
EmployerName: "cherokee",
Company: "ABC"
};
$http({
url: "http://localhost:212122/api/Values/PostEmployeeData",
dataType: 'json',
method: 'POST',
data: JSON.stringify(ipEmployerDetls),
headers: {
"Content-Type": "application/json"
}
}).success(function (response) {
$scope.object = response.data;
})
.error(function (error) {
alert(error.Message);
});
})();
WebAPI
using System.Web.Http;
using AttributeRouting.Web.Http;
namespace webAPITestProject.Controllers
{
[Route("api/Values")]
public class ValuesController : ApiController
{
retrieveEmployeeData empData = new retrieveEmployeeData();
retrieveProductDetails prodDetls = new retrieveProductDetails();
[Route("PostEmployeeData")]
[HttpPost]
public DataTable PostEmployeeData([FromBody] Employer empDetails)
{
DataTable dataTable = new DataTable { TableName = "MyTableName" };
dataTable = empData.getEmployeeData(empDetails);
return dataTable;
}
}
}
NOTE: I get NULL value in empDetails in webAPI method,but when I test the method in Postman,it has value.
Your routing attributes don't look right for how you've specified your $http API call.
Looks like you want the class-level attribute to be:
[RoutePrefix("api/Values")]
public class ValuesController : ApiController
Which will mean that PostEmployeeData has a route of api/Values/PostEmployeeData.
You'll also need to ensure that your properties in ipEmployerDetls directly map to your Employer class (which you haven't shown), so that model binding works correctly.
I am trying to send data from angular js to server.. Laravel5 is running on my server.. I can fetch data using this but can not send data.. My code is bellow
AngularJs Code:
var request = $http({
method: "get",
url: "http://www.myserver.com/json",
data: { email: $scope.email },
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})
request.success(function (data) {
alert(data.email);
});
Server code :
route is Route::get('json','JsonController#Json_login');
Controller code is
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Input;
class JsonController extends Controller
{
public function Json_login()
{
$email = Input::get('email');
$arr_Id_Status=array('email'=>$email);
echo json_encode($arr_Id_Status);
}
}
But it giving me null alert
Sounds like you should be using a POST rather than a GET request. You would need to create an appropriate POST route on your server but it's pretty much the same syntax on the client side, just change GET to POST.
var request = $http({
method: "POST",
url: "http://www.saadetera.com/json",
data: { email: $scope.email },
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function (data) {
alert(data.email);
});
Not used Laravel for a while but it would be something like:
Route::post('json','JsonController#handleLoginRequest');
Ideally, sending data will require a POST method while fetching will be using a GET method. Let's make the complete flow assuming you want to call a controller called your_controller and use its your_method function :
This suits for Laravel 5
Laravel Controller :
use Illuminate\Http\Request;
public function your_method(Request $request)
{
$data = $request->input(my_data);
//Server side data processing here
//Returning Json or anything else here
return response()->json(your_answer_here);
}
Route :
Route::post('your_url', ['uses' => 'your_controller#your_method']);
AngularJS : Here is the chunk of code allowing data sending, it requires $http service. Let's assume your data is contained in the my_data object.
$http.post('your_url', my_data)
.then(you_callback_success, your_callback_fail);
I am trying to send some json data from angular ng grid to spring mvc controller,but i am getting error as 400 (Bad request) The request sent by the client was syntactically incorrect. .
This is my Request Paylod:
[{"orderId":1,"orderTitle":"Xcel","orderDetail":"cash","orderType":"Xcel","orderPriority":"22.0","retailerId":0,"orderRefno":"9.900499743E9","customerName":"high","customerContactno":"pen drive","customerEmailId":"nutral","paymentType":"iffu#gmail.com","orderStatus":"pen drive","reciptDate":null,"bayNumber":"Xcel","deliveredDate":null,"deliveredBy":"Irfan","updatedOn":null,"pudoOutlet":null,"retailer":null,"outletId":0}]
here is my spring mvc controller:
#RequestMapping(value="/createorder",method=RequestMethod.POST,headers="Content-Type=application/json")
public #ResponseBody ModelAndView createOrder(#RequestBody Order order){
System.out.println("hiiiii"+order);
try{
orderDao.createOrder(order);
return new ModelAndView("product1.html");
}
catch(Exception e)
{
System.out.println(e);
}
return new ModelAndView("pr.html");
}
here is my angular controller from where i am posting:
$scope.save = function() {
console.log("hii inside save function");
console.log($scope.mySelections);
console.log("after myselection")
var d=$scope.mySelections;
console.log("hhhhh" +d);
$http({
method: 'POST',
url: './createorder',
headers: {'Content-Type': 'application/json'},
data:d
}).success(function (data)
{
$scope.status=data;
});
};
I am totally confused why i am getting this error ? Is it because i am sending some null values to spring mvc controller ? if yes how to solve this issue ?
Is Order an inner class? If so, try taking that class into its own file. Worked for me.
I have my data in json at controller, now i want to send that data to an post api call in service.
service - Article
At my controller :
var annotationScripts = {startOffset : range.startOffset , endOffset : range.endOffset};
Article.post({id: $routeParams.articleId},{data : annotationScripts}
);
At my service :
factory('Article', function($resource) {
return $resource('article/:id', {}, {
query: { method: 'GET', isArray: false },
post : { method: 'POST', params:{id : '#id'} , data : {#data}, headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
})
});
Why dont you use $resource out of the box features?
Here's a post example, with a simplified version of what you already have:
Resource service
factory('Article', function($resource) {
var Article = $resource('article/:id', {id: "#id"});
return Article;
});
Controller
var article = new Article();
article.startOffset = range.startOffset;
article.endOffset = range.endOffset;
article.$save();