I have a AngularJS app where I take in user input and store it in a painting objects and then send it to my spring boot back-end that will store it to the Mongodb server and return an id, however when I try go POST anything to the server i get an empty response back, even though the object gets stored in the server.
AngularJS code:
<!DOCTYPE html>
<html lang="en-US">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.1/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p>Name : <input type="text" ng-model="name"></p>
<h1>Hello {{name}}</h1>
<br>
<br>
<br>
URL : <input type="text" ng-model="painting.url"><br>
Artist : <input type="text" ng-model="painting.artist"><br>
ArtistInfo : <input type="text" ng-model="painting.artistInfo"><br>
Title : <input type="text" ng-model="painting.title"><br>
Dated : <input type="text" ng-model="painting.dated"><br>
Medium : <input type="text" ng-model="painting.medium"><br>
Dimensions : <input type="text" ng-model="painting.dimensions"><br>
Credit : <input type="text" ng-model="painting.credit"><br>
<button ng-click="submit()">Post</button>
<pre>{{painting | json}}</pre>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', ['$scope','$http', function($scope,$http) {
$scope.name = "";
$scope.painting = {
url: '',
artist: '',
artistInfo: '',
title: '',
dated: '',
medium: '',
dimensions: '',
credit: ''
};
$scope.submit = function(){
console.log(JSON.stringify($scope.painting));
$http({
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
url: 'http://localhost:8080/paintings',
data: $scope.painting
}).then(function (response) {
console.log(response);
}, function (response) {
console.log("Error");
console.log((JSON.stringify(response)));
});
//$http.post('http://localhost:8080/paintings', $scope.painting).catch(console.error);
};
}]);
</script>
</body>
</html>
SpringBoot Java POST Method:
#RequestMapping(method = RequestMethod.POST, value = "/paintings")
public String save(#RequestBody Painting painting){
repository.save(painting);
System.out.println("Function called");
return painting.getID();
}
PostMan Response:
Not sure why I'm getting an empty response when I check the console in a browser, even though the server is sending back a response.
I think you need to access the data property of the response,
.then(function (response) {
console.log(response.data);
}
What I ended up doing with the help of #Sajeetharan is edit my backend post request to
#RequestMapping(method = RequestMethod.POST, value = "/paintings")
public ResponseEntity<String> save(#RequestBody Painting painting){
repository.save(painting);
System.out.println("Function called");
JSONObject json = new JSONObject();
json.put("id",painting.getID());
return ResponseEntity.ok(json.toString());
}
Related
I'm trying to POST data to REST API but the server responds with an HTTP 405 error. I've tried many options like adding headers to the POST method, changing content type within the POST header but nothing seems to work out.
The exact response from the server is
{"detail":"Method \"POST\" not allowed."}.
HTML and JS code
<!DOCTYPE html>
<html>
<head>
<title>
New User Story
</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('postserviceApp', []);
app.controller('postserviceCtrl', function ($scope, $http) {
$scope.jiraLink = null;
$scope.reporter = null;
$scope.assignee = null;
$scope.Reviewer = null;
$scope.summary = null;
$scope.description = null;
$scope.storyPoints = null;
$scope.postdata = function (jiralink, reporter, assignee, reviewer, summary, description, storypoints) {
var data = {
jiraLink: jiralink,
reporter: reporter,
assignee: assignee,
Reviewer: reviewer,
summary: summary,
description: description,
storyPoints: storypoints
};
//Call the services $http.post('/userStory/story', JSON.stringify(data))
$http({
method: 'POST',
url: '/userStory/story',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'
},
data: data
}).then(function (response) {
if (response.data)
$scope.msg = "User story created Successfully!";
}, function (response) {
$scope.msg = "Couldn't create an User story";
$scope.statusval = response.status;
$scope.statustext = response.statusText;
$scope.headers = response.headers();
});
};
});
</script>
</head>
<body>
<div ng-app="postserviceApp" ng-controller="postserviceCtrl">
<div>
Jira Link : <input ng-model="jiralink" /><br/><br/>
Reporter : <input ng-model="reporter" /><br/><br/>
Assignee : <input ng-model="assignee" /><br/><br/>
Reviewer : <input ng-model="reviewer" /><br/><br/>
Summary : <input ng-model="summary" /><br/><br/>
Description : <input ng-model="description" /><br/><br/>
Story Points : <input ng-model="storypoints" /><br/><br/>
<input type="button" value="Create" ng-click="postdata(jiralink, reporter, assignee, reviewer, summary, description, storypoints)" /> <br/><br/>
</div>
<p>Output Message : {{msg}}</p>
<p>StatusCode: {{statusval}}</p>
<p>Status: {{statustext}}</p>
<p>Response Headers: {{headers}}</p>
</div>
</body>
</html>
models.py
from django.db import models
class Story(models.Model):
jiraLink = models.TextField(max_length=200)
reporter = models.TextField(max_length=50)
assignee = models.TextField(max_length=50)
Reviewer = models.TextField(max_length=50)
summary = models.TextField(max_length=50)
description = models.TextField(max_length=300, blank=True)
storyPoints = models.IntegerField(null=True, blank=True)
I'm not able to figure out where the problem. Any help is appriciated.
Struggling to get http:get to pull a request from a API server in an Ionic app, can anyone help with the code. Here is what I have:
<form ng-submit="getOrders()">
<label class="item item-input item-stacked-label">
<span class="input-label">Search Order #</span>
<input type="text" name="order number" placeholder="enter order number" ng-model="query">
</label>
<input class="button button-block button-positive" type="submit" name="submit" value="Submit">
</form>
$scope.getOrders= function(){
$http.get('http://example.com/api/booking/orders/'+ $scope.query).success(function(data) {
$scope.orders = [ data.data ];
$scope.query = query;
console.log(query);
})
}
Here are a few http get code blocks I have tried without success
//$http.get('http://example.com/api/booking/get/orders/').success(function(data) {
//$http({ url: 'http://example.com/api/booking/orders/', method: "GET", params: {query} }).success(function(data) {
//$http.get('http://example.com/api/booking/get/orders/+ $scope.query').success(function(data) {
//$http.get('http://example.com/api/booking/get/orders/121137').success(function(data) {
//$http.get('js/121137.json').success(function(data) {
Also, here is an example of some working POST code to an API which may provide some extra clues in performing a successful GET query from an API server:
https://plnkr.co/edit/w0cyfzGij8SgcsnbXqsj?p=catalogue
use promise as follows
.then(function(success){
//handle success
})
.catch(function(error){
//handle error
})
this is currect code.
$scope.getOrders= function(){
$http.get('http://example.com/api/booking/orders/'+$scope.query).success(function(data) {
$scope.orders = data.data;
console.log(data);
console.log($scope.query);
})
}
I have a form that looks like this:
<form id="myForm" ng-submit="submitForm()">
<select name="ItemName" ng-controller="ItemController">
<option value="" selected disabled>Select</option>
<option ng-repeat="item in items track by $index" value="{{item.Id}}">{{item.Name}}</option>
</select>
<input type="text" name="Description" />
<button type="submit">Submit</button>
</form>
My AngularJS FormController then does the following:
form.controller.js
app.controller('FormController', function($scope, $http) {
$scope.submitForm = function () {
$http({
method: 'POST',
url: '/Path/To/MVC/Action',
data: { json: JSON.stringify($('#myForm').serializeArray()) }
})
.success(function(data) {
console.log('success');
})
.error(function(error) {
console.log('failure);
});
};
});
I want my MVC controller to receive a json string that looks like this:
{
"Name": "some item name",
"Description": "some item description"
}
With serialize(), I got something like:
Name=some%20item%20name&Description=some%20item%20description
...and with serializeArray(), I got something like:
[{
name: "Name",
value: "some item name"
},
{
name: "Description",
value: "some item description"
}]
How do I get the JSON string in the format I'm looking for?
Is this what you are looking for? I am a little unclear with what items is, etc:
https://plnkr.co/edit/IFHNtxS226Hq0cCMJYi1?p=preview
$scope.submitForm = function(formData){
console.warn(formData);
$http({
method: 'POST',
url: '/Path/To/MVC/Action',
data: { json: formData }
})
.success(function(data) {
console.log('success');
})
.error(function(error) {
console.log('failure');
})
}
});
Are you using WebAPI?
You can replace your select for this:
<select id="selectId" type="text" ng-required="true" name="nameOfSelect" class="form-control" ng-model="yourModel.ObjectForThisSelect" placeholder="String Inside you Select"
ng-options="info.Value as info.Text for info in items>
</select>
then you should post back "yourModel" object, this way Angular when posting back will serialize only the selected option value.
Additionally in case you are using WebApi you can check in your WebApiConfig class, Register(HttpConfiguration config) method, that you are formatting Json strings in the desired format: i.e.
var jsonFormatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
jsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
jsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize;
jsonFormatter.SerializerSettings.ContractResolver = new DefaultContractResolver();
I am using MEAN JS, i am trying to edit the list items on the list page, but it shows the error as below. i have initiated the data using ng-init="find()" for the list and ng-init="findOne()" for individual data.
Error: [$resource:badcfg] Error in resource configuration for action `get`. Expected response to contain an object but got an array
HTML
Below i the form inside the controller where it initiates the find() and findOne().
<div ng-controller="OrdersController" ng-init="find()">
<div>
<div class="order-filter">
<div ng-repeat="order in orders">
<form ng-init="findOne()" name="orderForm" class="form-horizontal" ng-submit="update(orderForm.$valid)" novalidate>
<input type="text" class="" ng-model="order.title">
<input type="text" class="" ng-model="order.content">
<div class="form-group">
<input type="submit" value="Update" class="btn btn-default">
</div>
</form>
</div>
</div>
</div>
</div>
Controller
$scope.update = function (isValid) {
$scope.error = null;
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'orderForm');
return false;
}
var order = $scope.order;
order.$update(function () {
$location.path('orders/' + order._id);
}, function (errorResponse) {
$scope.error = errorResponse.data.message;
});
};
$scope.find = function () {
Orders.query(function loadedOrders(orders) {
orders.forEach(appendFood);
$scope.orders = orders;
});
};
$scope.findOne = function () {
$scope.order = Orders.get({
orderId: $stateParams.orderId
});
};
You need to check your Orders Service which probably is using $resource to provide your API requests (Orders.query)
It should look something like this:
function OrdersService($resource) {
return $resource('api/orders/:orderId', {
orderId: '#_id'
}, {
update: {
method: 'PUT'
}
});
}
The style may be different depending on which version of mean you're using. By default, the $resource query will expect an array of results, but if for some reason you've set "isArray" to false then it will expect an object.
https://docs.angularjs.org/api/ngResource/service/$resource
I am using angular 1.3.0 and bootstrap 3.2.0. I am trying to get data from asynchronously from my mysql database but I got some issue with bootstrap typeahead.
MY code index.html:
<input type="text" ng-model='locality' name="locality" typeahead="name for locality in getLocality($viewValue) | filter:$viewValue" typeahead-loading="loadingLocations" class="form-control size1 input-medium search-query"
placeholder="Enter Organization name/service">
</input>
main.js file for typeahead
$scope.getLocality = function(val) {
console.log(val);
var url = $rootScope.baseURL + '/api/location?locality=' + val;
console.log(url);
return $http.get(url, {
params: {
name: val,
sensor: false
}
}).then(function(response) {
var addresses = [];
angular.forEach(response.data.resulults, function(item) {
addresses.push(item.formatted_name);
});
return addresses;
});
};
When I was debugging this value will fine but i am not getting any auto suggestions please any one help me out of this problem.
It's working fine Thank u #tiblu
index.html file
<input type="text" ng-model='locality' name="locality"
typeahead="name for name in getLocality($viewValue)"
typeahead-loading="loadingLocations"
class="form-control size1 input-medium search-query"
placeholder="Enter Organization name/service">
</input>
.js file
$scope.getLocality=function(val){
console.log(val);
var url=$rootScope.baseURL + '/api/location?locality='+val;
console.log(url);
return $http.get(url,{
params: {
name: val,
sensor: false
}
}).then(function(response){
console.log(response);
console.log(response.data);
var addresses=[];
angular.forEach(response.data.data,function(item){
addresses.push(item.name);
//return item.formatted_name;
console.log(response.data);
});
return addresses;
/*return response.data.results.map(function(item){
return item.formatted_address;*/
});
};