0
votes

i'm trying to create login form with nuxtjs as front end and slim php as backend api, when i tried to access the API, i see the request method that i send is OPTIONS not POST, and in chrome dev console error shown that the request is blocked (CORS). I know i have to set Access-Control-Allow-Methods add OPTIONS into it, but still failed, where to set that in nuxt js(nuxt.config) or slim php?

I have tried to access the api from postman and it work's just fine, i can see Access-Control-Allow-Methods headers has OPTIONS in it, but still it failed when i tried in vue apps

commons.app.js:434 OPTIONS http://localhost:8080/login 401 (Unauthorized)

Access to XMLHttpRequest at 'http://localhost:8080/login' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Code from slim php (API)

routes.php

// login routes
$app->post('/login', function (Request $request, Response $response, array $args) {

        $input = $request->getParsedBody();
        $sql = "SELECT * FROM groups
                LEFT JOIN users_groups ON groups.groups_id = users_groups.users_groups_id
                LEFT JOIN users ON users_groups.users_groups_id = users.id
                WHERE users.email = :email";
        $sth = $this->db->prepare($sql);
        $sth->bindParam("email", $input['email']);
        $sth->execute();
        $user = $sth->fetchObject();

        // verify email address.
        if (!$user) {
            $container->get('logger')->info("Error trying to login with email : ".$input['email']);
            return $this->response->withJson(['error' => true, 'message' => 'These credentials do not match our records.']);
        }

        // verify password.
        if (!password_verify($input['password'], $user->password)) {
            $container->get('logger')->info("Error trying to login with password : ".$input['password']);
            return $this->response->withJson(['error' => true, 'message' => 'These credentials do not match our records.']);
        }

        // cek apakah sudah login sebelumnya hari ini untuk user ini
        $absensiSql = "SELECT * FROM users_presensi WHERE user_id = :userID";
        $sth = $this->db->prepare($absensiSql);
        $sth->bindParam("userID", $user->id);
        $sth->execute();
        $absensi = $sth->fetchObject();

        // jika belum absen, masukan user ke absensi
        if(!$absensi){
            $status = 1;
            $absensiSql = "INSERT INTO users_presensi(user_id, statuss) VALUES (:userID, :statuss)";
            $sth = $this->db->prepare($absensiSql);
            $sth->bindParam("userID", $user->id);
            $sth->bindParam("statuss", $status);
            $sth->execute();
            // $absensi = $sth->fetchObject();s
        }

        $settings = $this->get('settings'); // get settings array.

        $token = JWT::encode(['id' => $user->id, 'email' => $user->email, 'level' => $user->groups_level], $settings['jwt']['secret'], "HS256");

// i already set the header here
        return $this->response
        ->withHeader('Access-Control-Allow-Origin', '*')
        ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
        ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
        ->withHeader('Set-Cookie', "token=$token; httpOnly")
        ->withJson(['token' => $token]);

    })->setName('login');

my nuxtjs auth config nuxt.config.js

/*
  ** Nuxt.js modules
  */
  modules: [
    '@nuxtjs/vuetify',
    // Doc: https://axios.nuxtjs.org/usage
    '@nuxtjs/axios',
    '@nuxtjs/pwa',
    '@nuxtjs/eslint-module',
    '@nuxtjs/auth'
  ],
  /*
  ** Axios module configuration
  ** See https://axios.nuxtjs.org/options
  */
  axios: {
  },

  /**
   * set auth middleware
   */
  router: {
    middleware: ['auth']
  },
  auth: {
    strategies: {
      local: {
        endpoints: {
          login: { url: 'http://localhost:8080/login', method: 'post', propertyName: 'token' }
        }
        // tokenRequired: true,
        // tokenType: 'bearer'
      }
    }
  }

method login from login.vue

   loginPost: function () {
      this.$auth.loginWith('local', {
        data: {
          username: this.loginData.username,
          password: this.loginData.password
        }
      })
    }

in postman, the result is token itself, and i think there shouldn't be cors error happen, but who's know.

1

1 Answers

1
votes

I don't know about other browsers, but I know that Chrome does not support using localhost in your Access-Control-Allow-Origin header. What you should do is in your dev environment only tell it to accept all origins ->withHeader('Access-Control-Allow-Origin', '*')

The OPTIONS request is what is sent out in preparation for the browser sending out the real request to determine what the CORS rules are.