angular $http post not sending data for service - angularjs

I´m trying user $http post in angular, where the rest service receive an object. The data is a Json where I need pass with parameter for method in service.
My angular code (it´s doesn´t work for me):
$http({
method:'POST',
url:request.url,
data: JSON.stringify(objcsr);
headers: {'Content-Type':'application/json; charset=utf-8'}
}).then(function(objS){
alert('Success :- '+JSON.stringify(objS));
},function(objE){
debugger;
alert('error:- '+JSON.stringify(objE));
});
If I comment the row data, the comunication with service it´s ok:
$http({
method:'POST',
url:request.url,
//data: JSON.stringify(objcsr);
headers: {'Content-Type':'application/json; charset=utf-8'}
}).then(function(objS){
alert('Success :- '+JSON.stringify(objS));
},function(objE){
debugger;
alert('error:- '+JSON.stringify(objE));
});
My method in service:
public UserAccessDTO Authenticate(AuthenticationDTO authentication)
{
.....
}

I hope the object you are passing in data parameter is same as AuthenticationDTO class, its properties must be same. If that is fine then try running this.
$http.post('url',JSON.stringify(data),{headers: {'Content-Type':'application/json'}})
.success(function (data) {
alert('Success :- '+JSON.stringify(data));
});
As well I am assuming that you have included [HttpPost] attribute before your method. like this:
[HttpPost]
public UserAccessDTO Authenticate(AuthenticationDTO authentication)
{
.....
}

Related

Angular: $http change method on adding data with post

I am using fuse template and accessing my web service by using $http, its working fine if i am using method: 'POST' without send any data but whenever i am adding some data with post like: data: {text:'test'} and send request to my web service its change the method type POST to OPTIONS.
My Code:
$scope.submit = function(){
$http({
method: 'POST',
url: 'http://www.example.com/api-link',
data: {test: 'hello'},
header: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function(result){
console.log(result);
});
}
When i am checking in browser network its showing method type OPTIONS. Can anyone please tell what is wrong in my code?
Thanks

angular laravel nginx 400 Bad Request

Help, I've got 400 error on POST and or PUT method, but GET works just fine,
I'm using angular as front end and laravel as API, my server is using nginx,
I've used CORS and I everything works fine on my local vagrant which is running on apache.
I'm sure I have my route set correctly, here's some of it from the module I use:
Route::group(array('prefix'=>'/api', 'middleware' => 'cors'),function(){
Route::post('/create_level', 'LevelController#store');
Route::get('/read_level', 'LevelController#index');
Route::get('/read_level/{id}', 'LevelController#show');
Route::put('/read_level/{id}', 'LevelController#update');
Route::delete('/read_level/{id}', 'LevelController#destroy');
here's part of my angular service:
app.service("edulevelService", function ($http, $q, $rootScope)
{
edu.updateEdulevel = function(id, edu){
var deferred = $q.defer();
$http.put($rootScope.endPoint + 'read_level/'+ id, edu)
.success(function(res)
{
deferred.resolve(res);
})
.error(function(err, stat){
deferred.reject(err);
console.log('error code: Ser-UEDU');
});
return deferred.promise;
}
edu.createEdulevel = function(edu){
var deferred = $q.defer();
$http.post($rootScope.endPoint + 'create_level', edu)
.success(function(res)
{
deferred.resolve(res);
})
.error(function(err, stat){
deferred.reject(err);
console.log('error code: Ser-CEDU');
});
return deferred.promise;
}
....
oh I forgot to mention different method cause different error code POST cause 405, PUT cause 400, and I've tried using Postman:
POST is working using text type and return 405 using application/json,
but when I tried
PUT method even though it return 200 I only got NULL data entered to my db (text type), and if I use application/json it return 400
Please Help
Finally found solution:
change $http.post to:
$http({
method: "post",
url: $rootScope.endPoint + 'create_level',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param({ .... })
})
somehow it works, exept on my login page which using stellizer to do post method and i can't find how should I change it without breaking all the function...
any one?
I only need to add:
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
and
data: $.param({ ...... })

What is type of data angular sending?

What is type of data angular sending? I use laravel + angular. I`m trying, but this script return 405 error. Method not allowed.
.controller('adminCtrl', function( $scope, $http ){
$scope.collection = [];
$scope.newData = [];
$scope.newrecord = function() {
$scope.collection.push($scope.newData);
$http({
url: '/newrecord',
method: "POST",
data: $.param($scope.collection),
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).success(function(data){
console.log(data);
})
}
})
You are getting 405 - Method not Allowed because the server you are sending your request does not have POST it the white list of methods allowed to be used to perform requests to that given API.
It's not an angularJS issue, it's a server configuration issue.
$http sends data as json.
You do not need to serialize params using "$.param", data is plain javascript object, which is send to your REST endpoint.
So attach just "$scope.collection) and do not set Content Type manually, it is json by default.
POST can be send also with convenience method.
$http.post('/someUrl', data, config).then(successCallback, errorCallback);

How to send data from angular js to laravel 5 server

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

Angular http call fails with content-type json

Here is my service:
home.factory("homeService", function ($http, $q) {
var service =
{
getAssets: function () {
var deferred = $q.defer();
var response = $http({
method: "post",
dataType: "json",
data: '',
headers: {
'Content-Type': "application/json"
},
url: "http://localhost/myWeb/services/reports_ws.asmx/getData",
});
response.success(function (data) {
deferred.resolve(data);
});
response.error(function (data) {
alert('Error');
});
// Return the promise to the controller
return deferred.promise;
},
}
return service;
I am getting 500 error from the server when I use application/json for the content. using plain/text works fine and data is returned, but in an xml format although the server sends data back in json format. I have tested it in Chrome, everything works fine. I also noticed that Chrome sends request using "application/x-www-form-urlencoded" for content-type. I tried it too, but still got data in xml. Please help.
Thanks
keep trying with the following:
header: { "Content-Type" : "application/x-www-form-urlencoded"}
Please notice that this applies only for the header of the request, not the response. The response depends on your backend (server side).
Several ways are available to return JSON data in the response depending of the type of server you are using.

Resources