我正在使用chriskacerguis/codeigniter-restserver在 Codeigniter 中创建一个简单的 REST API 。我已经成功创建了一个登录方法并使用邮递员对其进行了测试,它可以工作,但是我创建了一个简单的登录页面来使用 Jquery AJAX 使用 API,但是当我尝试通过它发送但$this->post()
无法阅读它但它适用于邮递员。
控制器
<?php
defined('BASEPATH') or exit('No direct script access allowed');
require APPPATH . 'libraries/REST_Controller.php';
require APPPATH . 'libraries/Format.php';
use Restserver\Libraries\REST_Controller;
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
class Api extends REST_Controller
{
public function user_login_post()
{
$req = $this->post(); // always empty
if (empty($req)) {
$status = parent::HTTP_EXPECTATION_FAILED;
$response = ['status' => $status, 'msg' => 'Missing data!'];
$this->response($response, $status);
exit();
}
$user = $this->User_model->get($req['email']);
if (empty($user)) {
$status = parent::HTTP_NOT_FOUND;
$response = ['status' => $status, 'msg' => 'Email does not exist!'];
$this->response($response, $status);
exit();
}
if (md5($req['password']) != $user->password) {
$status = parent::HTTP_FORBIDDEN;
$response = ['status' => $status, 'msg' => 'Invalid email or password!'];
$this->response($response, $status);
exit();
}
// Generate token
$tokenData['id'] = $user->user_id;
$tokenData['email'] = $user->email;
$tokenData['type'] = 'user';
$token = AUTHORIZATION::generateToken($tokenData);
$status = parent::HTTP_OK;
$response = ['status' => $status, 'token' => $token, 'logged_in' => true];
$this->response($response, $status);
}
}
这是我用来向上述方法发送请求的 JS 代码
$('#submit').click(function (e) {
e.preventDefault();
const url = "<?= base_url() ?>" + 'api/user_login';
$.ajax({
type: 'POST',
url: url,
data: {
"email": "test@gmail.com",
"password": "password"
},
dataType: 'json',
cache : false,
processData: false,
success: function (res) {
console.log(res);
},
error: function (err) {
console.log(err);
}
})
});
我无法在服务器端获取数据。任何帮助,将不胜感激。