doukang7486 2017-10-17 12:28
浏览 83

Vue laravel api登录无法正常工作

I am trying to login with a user from the frontend built with Vue 2. This is the component with the login form:

<template>
    <div>
      <section class="section">
          <div class="container">
            <div class="form column is-half is-offset-one-quarter">
              <div class="control">
                <input class="input is-large" type="email" v-model="email">
                <label>E-post</label>
              </div>
              <div class="control">
                <input class="input is-large" type="password" v-model="password">
                <label>Passord</label>
              </div>
              <div @click.prevent="save" class="button hero-button is-medium is-primary">
                Logg in
              </div>
            </div>
          </div>
      </section>
    </div>
</template>

<script>
  export default {
    name: 'login',
    data() {
      return {
        email: '',
        password: '',
      };
    },
    methods: {
      save() {
        const form = new FormData();
        form.append('email', this.email);
        form.append('password', this.password);

        this.$backend.post('/user/login', form, {
        }).then(() => {
            this.failed = false
        }, () => {
            this.failed = true
        });
      }
    }
  };
</script>

If I try to login with that form I always get a response:

{"error":{"code":"GEN-UNAUTHORIZED","http_code":401,"message":"Unauthorized"}}

But, when I have tested that in Postman, I get a token back, when I try to login with the same credentials that I use in the Vue form. What am I doing wrong there?

This are the routes in the Laravel backend:

Route::group(['prefix' => 'api', 'middleware' => ['api']], function () {
    Route::group(['prefix' => 'v0'], function () {
        Route::resource('taxonomy', 'Api\TaxonomyController');
        Route::resource('type', 'Api\ContentTypeController');
        Route::get('options/{option}', 'Api\OptionsController@getPage');
        Route::resource('menu', 'MenuController');
        Route::get('preview/{id}', 'PreviewController@show');

        Route::group(['prefix' => 'user'], function () {
            Route::post('register', 'Api\UserController@register');
            Route::post('login', 'Api\UserController@login');
            Route::group(['middleware' => 'token'], function () {
                Route::get('/', 'Api\UserController@index');
                Route::get('data', 'Api\UserController@getUser');
            });
        });
    });
});

And this is the login function:

    public function login(Request $request)
    {
        $authenticatedUser = $this->authenticate($request->email, $request->password);

        if (!$authenticatedUser) {

            $remoteAuthenticated = $this->checkWplUser($request->email, $request->password);
            if (!$remoteAuthenticated) {

                return $this->response->errorUnauthorized();
            }
        }
        return $this->issueToken($request->email, $request->password);
        //return $this->returnUserResponse();
    }

When I have tried to do dd($request->all()); in the login function to see what am I getting from the frontend, I got a response:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

I am using barryvdh/laravel-cors package for cors. This is how it is setup. This is the kernel file:

protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Barryvdh\Cors\HandleCors::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
        ],

        'api' => [
            'throttle:60,1',
            \Barryvdh\Cors\HandleCors::class,
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'token' => \App\Http\Middleware\AuthenticateToken::class,
        'jwt.auth' =>  \Tymon\JWTAuth\Middleware\GetUserFromToken::class,
        'jwt.refresh' =>  \Tymon\JWTAuth\Middleware\RefreshToken::class,
    ];

And this is what I have in the config/cors.php file:

'supportsCredentials' => false,
'allowedOrigins' => ['*'],
'allowedHeaders' => ['*'],
'allowedMethods' => ['*'],
'exposedHeaders' => [],
'maxAge' => 0,

What am I doing wrong?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 使用EMD去噪处理RML2016数据集时候的原理
    • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
    • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
    • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
    • ¥15 如何在炒股软件中,爬到我想看的日k线
    • ¥15 seatunnel 怎么配置Elasticsearch
    • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
    • ¥15 (标签-MATLAB|关键词-多址)
    • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
    • ¥500 52810做蓝牙接受端