我一直致力于正常运行的REST API。通过像Postman这样的客户端,只要我使用x-www-form-urlencoded
但是现在我正试图将它与Angular联系起来。我可以提出一个GET请求就好了,POST就是让我感到高兴的事情。
这是我的scratch指令在Angular .js中执行脏工作(我知道我需要为此创建一个服务):
app.directive('addGoal', function($http) {
return {
restrict: 'E',
templateUrl: 'js/templates/add-goal.html',
link: function(scope) {
scope.submit = function(data) {
data = {
goal: {
summary: "asdf",
details: "asdf",
start_date: "2014-01-01",
end_date: "2014-01-02"
}
};
console.log(data);
$http({
url: 'http://localhost:8000/v1/goal/',
method: 'POST',
data: data,
headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
}).
success(function() {
console.log(data);
}).
error(function() {
console.log('error');
});
};
}
};
});
调用被触发且.success() function
正常运行,但数据未在我的API中发布,因此未保存到数据库中。
当我收到回复时,它的行为就像格式化不对,因为它在验证时出错:
{"error":true,"message":{"summary":["The summary field is required."],"details":["The details field is required."],"start_date":["The start date field is required."],"end_date":["The end date field is required."]}}
仅供参考,这是我的Controller在Laravel中执行API工作的store()函数:
public function store()
{
$goal = new Goal;
$goal->summary = Request::get('summary');
$goal->details = Request::get('details');
$goal->user_id = Auth::user()->id;
$start_date_entered = Request::get('start_date');
$end_date_entered = Request::get('end_date');
$goal->start_date = date('Y-m-d', strtotime($start_date_entered));
$goal->end_date = date('Y-m-d', strtotime($end_date_entered));
$validation = Validator::make(Request::all(), [
'summary' => 'required|max:255',
'details' => 'required|max:255',
'start_date' => 'required|date',
'end_date' => 'required|date'
]);
if ($validation->fails())
{
$messages = $validation->messages();
return Response::json(array(
'error' => true,
'message' => $messages),
200
);
}
else
{
$goal->save();
return Response::json(array(
'error' => false,
'goal' => $goal->toArray()),
200
);
}
}
我创建了一个这样的测试路线:
Route::post('/test', function()
{
// First we fetch the Request instance
$request = Request::instance();
// Now we can get the content from it
$content = $request->getContent();
var_dump($content);
});
令人惊讶的是,我的回复看起来像这样:
string(94) "{"goal":{"summary":"asdf","details":"asdf","start_date":"2014-01-01","end_date":"2014-01-02"}}"
如果成功功能正在触发,它就会触及API,对吗?我怎样才能解决这个问题以找出真正的问题?我被困在我应该去的地方,将这些数据放入API,以便它可以正确存储它,就像在REST客户端中一样。
修改
经过审核,实际问题涉及我设置Laravel的方式,而且无法理解JSON是否被传入。一个简单的修复涉及将Request::get
更改为Input::json()->get()
:
$goal->summary = Input::json()->get('summary');
答案 0 :(得分:1)
我出于此目的使用Telerik fiddler:http://www.telerik.com/fiddler。它提供了以下信息。
它还允许我们通过修改方法和数据来重放给定的请求,以检查服务对不同输入的行为。
希望它有所帮助。
此外, 我认为即使你改变了如下的数据格式,也应该有效。
data = {
summary: "asdf",
details: "asdf",
start_date: "2014-01-01",
end_date: "2014-01-02"
};