gpt4 book ai didi

javascript - 带有 Rails API 的 Angularjs 休息后 400(错误请求)

转载 作者:行者123 更新时间:2023-12-03 05:18:12 25 4
gpt4 key购买 nike

你好,我制作了一个rails api和angularJs的项目,我发现了以下错误。

angular.js:11821 POST http://localhost:3000/people 400 (Bad Request)

我找不到原因。

代码如下。

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

感谢您的聆听

最佳答案

我看不到您的 person_params 定义,但如果它像由 Rails 生成器生成的那样,则您缺少将参数包装在 person 哈希中

var data = $.param({person: 
{ name: $scope.name,
age: $scope.age,
gender:$scope.gender,
lonlat:$scope.lonlat }
});

关于javascript - 带有 Rails API 的 Angularjs 休息后 400(错误请求),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41521416/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com