我试图从我的AngularJS-app发送一个POST请求到一个独立的Laravel后端(在localhost上),但无法弄清楚X-CSRF-TOKEN之类的东西。至少我认为这就是问题所在。
我总是在控制台中收到这个错误:
POST http://localhost/public/drinks 419 (unknown status)我已经在我的AngularJS应用程序的index.html中添加了以下内容:
<script>angular.module("myCaffeineIntake").constant("CSRF_TOKEN", '{{ csrf_token() }}');</script>下面是我的控制器中的代码:
$scope.answer = function(newdrink, CSRF_TOKEN) {
newdrink._token = CSRF_TOKEN;
newdrink._method = "post";
$http({
method : "POST",
url : "http://localhost/public/drinks",
data : newdrink
}).then(function mySuccess(response) {
}, function myError(response) {
console.log("error");
}
);还有我的Laravel-controller:
public function store(Request $request)
{
$drink = new Drink;
$this->validate(request(),[
'Name' => 'required',
'Size' => 'required',
'Caffeine' => 'required',
'Url' => 'required'
]);
Drink::create([
'Name' => request('Name'),
'Size' => request('Size'),
'Caffeine' => request('Caffeine'),
'Amount' => 0,
'Url' => request('Url'),
'created_at' => time(),
'updated_at' => time(),
]);
}我错过了什么?
发布于 2017-09-20 02:01:45
您不会返回该请求中的任何内容。
public function store(Request $request)
{
//$drink = new Drink; //Don't know why this is here like that, so removed it
$this->validate(request(),[
'Name' => 'required',
'Size' => 'required',
'Caffeine' => 'required',
'Url' => 'required'
]);
$drink = Drink::create([
'Name' => request('Name'),
'Size' => request('Size'),
'Caffeine' => request('Caffeine'),
'Amount' => 0,
'Url' => request('Url'),
'created_at' => time(),
'updated_at' => time(),
]);
//Maybe add the following
return response()->json([
'drink' => $drink,
]);
}让我解释一下我刚才做了什么,我将var $drink赋值给新Drink的创建,以便它返回新的Drink模型,然后将其作为json响应传递,现在您可以在success回调中捕获它
编辑:我对您的角度控制器做了一些更改,只需在$scope中捕获所有表单数据,将ng-model="drink.changeThisToAnyName"放入表单的每个input中,然后将其作为JSON传递给ajax post,请参见示例:
$scope.answer = function() {
$http.post('/public/drinks', {
data: $scope.drink,
}).then(function mySuccess(response) {
}, function myError(response) {
console.log("error");
}
);https://stackoverflow.com/questions/46305028
复制相似问题