首页 > 解决方案 > POST 在 CodeIgniter 中不工作,而 GET 工作正常

问题描述

我在 CodeIgniter 中使用 POST 时遇到了这个问题,如果我切换到 GET,它就无法正常工作。

登录控制器

public function login_check(){
    print_r($this->input->post());
    if($this->input->post('email')!=NULL){
        echo '1';
    }
    else{
        header('Content-Type: application/json');
        echo json_encode( array('a' => $this->input->post('email')));
}

CSRF 在配置文件中设置为 false,而基本 url 设置为http://localhost/xyz/

.htaccess

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

路线

$route['api/login-check'] = 'login/login_check';

如果我$this->input->get('email')在邮递员中设置方法 GET 时设置,那绝对没问题。

我错过了什么?对此的任何帮助将不胜感激。

编辑:

邮递员的回复:

Array() {"a":null}

标签: phpcodeignitercodeigniter-3

解决方案


代码完全按照您的要求执行。

你的代码分解就像......

If I get something from $this->input->post('email') then 
     echo '1';
else if $this->input->post('email') is NULL
     then assign NULL to a and return it in a json_encoded array.

按照你的代码,它可能意味着......

public function login_check(){
    print_r($this->input->post());
    if($this->input->post('email') == NULL){ // This was != 
        echo '1';
    }
    else{
        header('Content-Type: application/json');
        echo json_encode( array('a' => $this->input->post('email')));
}

唯一的变化是在 if 语句中将 != 更改为 ==。

其中一个“盯着它看太久,从来没有看到它”简单的逻辑错误:)

更好的建议是使用类似...

public function login_check(){
    print_r($this->input->post());

    if($this->input->post('email')){
        header('Content-Type: application/json');
        echo json_encode( array('a' => $this->input->post('email')));
        exit();
    }
    else {
        // Handle the case where no email was entered.
        echo '1';
    }
}

这应该让你回到正轨。

更新:我已经在邮递员中尝试过(刚刚安装了它),对于 POST,您需要像使用 GET 一样在 Body 下设置键/值,而不是在 Headers 下设置,如果这也是您所缺少的。


推荐阅读