Hey there, I'm currently working on a project involving Rails API and AngularJs, and I've encountered the following error.
angular.js:11821 POST http://localhost:3000/people 400 (Bad Request)
Unfortunately, I haven't been able to figure out why this error is occurring.
Below is the code snippet:
Rails Controller
# POST /people
def create
@person = Person.new(person_params)
if @person.save
render json: @person, status: :created, location: @person
else
render json: @person.errors, status: :unprocessable_entity
end
end
AngularJS
$scope.SendData = function () {
// use $.param jQuery function to serialize data from JSON
var data = $.param({
name: $scope.name,
age: $scope.age,
gender:$scope.gender,
lonlat:$scope.lonlat
});
var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
}
$http.post('http://localhost:3000/people', data, config)
.then(function (data, status, headers, config) {
$scope.PostDataResponse = data;
})
.catch(function (data, status, header, config) {
$scope.ResponseDetails = "Data: " + data +
"<hr />status: " + status +
"<hr />headers: " + header +
"<hr />config: " + config;
});
};
Html
<div ng-app="myApp" ng-controller="person">
<div class="modal-body">
<div class="form-group">
<label for="exampleInputEmail1">Name:</label>
<input type="text" class="form-control" name="name" ng-model="name" placeholder="Email">
</div>
<div class="form-group">
<label for="exampleInputEmail1">age:</label>
<input type="text" class="form-control" name="age" ng-model="age" placeholder="Email">
</div>
<div class="form-group">
<label for="exampleInputEmail1">gender:</label>
<input type="text" class="form-control" name="gender" ng-model="gender" placeholder="Email">
</div>
<div class="form-group">
<label for="exampleInputEmail1">lonlat:</label>
<input type="text" class="form-control" name="lonlat" ng-model="lonlat" placeholder="Email">
</div>
<button ng-click="SendData()"
class="btn btn-default">Submit</button>
{{ PostDataResponse }}
Thank you for your attention.