无法访问api post方法,始终请求选项

时间:2019-07-28 17:40:13

标签: php vue.js axios slim nuxt.js

我正在尝试使用nuxtjs作为前端并且使用slim php作为后端api创建登录表单,当我尝试访问API时,我看到发送的请求方法是 OPTIONS 而不是< strong> POST ,并且在chrome dev控制台错误显示请求被阻止(CORS)。 我知道我必须设置 Access-Control-Allow-Methods 并添加 OPTIONS ,但是仍然失败,无法在nuxt js(nuxt.config)或slim中进行设置php?

我尝试从邮递员访问api,它的工作正常,我可以看到 Access-Control-Allow-Methods 标头中有OPTIONS,但在vue中尝试时仍然失败应用

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.

苗条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', 'http://localhost:3000')
        ->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');

我的nuxtjs身份验证配置 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'
      }
    }
  }

login.vue中的方法登录

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

在邮递员中,结果是令牌本身,我认为不应发生cors错误,但谁知道呢。

1 个答案:

答案 0 :(得分:1)

我不了解其他浏览器,但我知道Chrome不支持在Access-Control-Allow-Origin标头中使用localhost。您应该做的是在开发环境中仅告诉它接受所有来源->withHeader('Access-Control-Allow-Origin', '*')

OPTIONS请求是为了发送给浏览器以发送实际请求以确定CORS规则而准备的。