问题
I'm creating an Angular app with a separate Laravel backend. I want to User auth, specifically User registration.
I'm getting the following errors:
Error from frontend app:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Error when trying to create new user from DHC:
Endpoint:
my_apps_api.localhost/api/auth/register
Post Data:
{
"username" : "myusername"
"password" : "12345"
}
TokenMismatchException in VerifyCsrfToken.php
I think this is because I need to generate a token from my angular app to pass back to Laravel, but am not sure how to do that, or if that is even the problem.
How can I generate a token such that I can create a new user?
Frontend Angular App:
SignUp Controller:
$scope.submit = function() {
Auth.signup({
username: $scope.user.username,
password: $scope.user.password
}).success(function(res) {
Auth Service:
signup: function(params) {
return $http({
method: 'POST',
url: authurl + 'auth/register',
data: params,
cache: true
});
}
Laravel API:
Route::group(['middleware' => 'cors'], function(\Illuminate\Routing\Router $router) {
...
$router->controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController'
]);
Note: Looking through the Laravel Routing docs, I know you can generate the token as such:
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
But am not sure how to do that from an external frontend app posting to Laravel.
回答1:
Based on you error:TokenMismatchException in VerifyCsrfToken.php You must turn of Csrf checks in middleware or send Csrf token in request.
If you want crsf in token in requet you should get it from server with ajax, or in html if you are fetching html from server. On server side crsf token is generated with helper function: csrf_token()
来源:https://stackoverflow.com/questions/33189948/creating-a-sign-up-token-for-laravel-app-from-separate-frontend-app