Hallo i have a tasks from college to create
elearning (me as backend) but i have problem when i deploy it to vps it's always getting error that said 'CORS NOT ALLOWED'.
Im using:
- Codeigniter3
- Library ci rest server (criskagruice)
- JWT
- NGINX
- simple login xhr with github.io
My structure of code is
ALL ENDPOINT/Class (.php) extends to
Token.php extends to
REST_Controller.php (library).
Here are ma code:
Login page (github.io)
Code:
let xhr = new XMLHttpRequest();
xhr.open('POST', 'https://IP_VPS/elearning/auth/login');
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
console.log(this.response);
}
}
xhr.send('email='+email.value+'&password='+password.value);
Token.php (child of REST_Controller)
Code:
<?php
// load library rest server
use Restserver\Libraries\REST_Controller;
require APPPATH . 'libraries/REST_Controller.php';
require APPPATH . 'libraries/Format.php';
// load library rest server
use \Firebase\JWT\JWT;
require APPPATH . 'libraries/JWT.php';
require APPPATH . 'libraries/BeforeValidException.php';
require APPPATH . 'libraries/ExpiredException.php';
require APPPATH . 'libraries/SignatureInvalidException.php';
defined('BASEPATH') OR exit('No direct script access allowed');
class Token extends REST_Controller {
private $_secretkey = 'elearning';
private $_token;
public function __construct(){
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400');
parent::__construct();
$this->load->model('m_users', 'user');
}
......................................................
} ?>
Auth.php (child of Token.php)
Code:
<?php
require APPPATH . 'controllers/api/Token.php';
defined('BASEPATH') OR exit('No direct script access allowed');
class Auth extends Token {
public function __construct() {
parent::__construct();
$this->load->library('form_validation');
}
public function login_post() {
// terima data dari form
$email = $this->post('email');
$password = $this->post('password');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'required');
// form validation false akan merespon input form yang false
if (!$this->form_validation->run()) {
$form_error = $this->form_validation->error_array();
$this->response([
'status' => FALSE,
'message' => 'form tidak lengkap',
'error' => ['form_error' => $form_error]
], 404);
}
// -------- AKAN DIEKSEKUSI JIKA FORM INPUT LENGKAP ------
// cek apakah user ada pada database
$user_detail = $this->user->getUser($email);
if (!$user_detail) {
$this->response([
'status' => FALSE,
'message' => 'Email/Password Salah'
], 404);
}
// response 404 jika user tidak ada
$hash_password = $user_detail['password'];
if ( !password_verify($password, $hash_password) ) {
$this->response([
'status' => FALSE,
'message' => 'Email/Password Salah',
], 404);
}
// menyiapkan token
$token = parent::generateToken($user_detail);
// menyapkan response json
$response = [
'status' => TRUE,
'message' => 'berhasil login',
'data' => [
'name' => $user_detail['name'],
'email' => $user_detail['email'],
'user_role' => $user_detail['type'],
'token' => $token
]
];
// response 200 user berhasil masuk
$this->response($response, 200);
}
}
?>
/etc/nginx/sites-available/default
Code:
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
#try_files $uri $uri/ =404;
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
#
# Custom headers and headers various browsers *should* be OK with but aren't
#
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
#
# Tell client that this pre-flight info is valid for 20 days
#
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
if ($request_method = 'POST') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
}
if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
}
}
# pass PHP scripts to FastCGI server
#
location ~ \.php$ {
include snippets/fastcgi-php.conf;
#
# # With php-fpm (or other unix sockets):
fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
# # With php-cgi (or other tcp sockets):
# fastcgi_pass 127.0.0.1:9000;
}
# codeigniter elearning
location /elearning {
try_files $uri $uri/ /elearning/index.php;
}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
location ~ /\.ht {
deny all;
}
Im actually super new at creating API & deploying and don't know what should i do now. In these code above which is wrong ? Thanks Anyway