【问题标题】:Fetch post method is not working - react native获取帖子方法不起作用-本机反应
【发布时间】:2018-12-24 09:47:54
【问题描述】:

我有一个奇怪的问题。这里第一种方法不起作用。在这里,它给出了关键用户名的错误。它给出了用户名是必需的错误。但是第二种方法有效。两者基本相同。这里可能有什么问题

P.S 服务器中的 api 是简单的 sql。我没有在代码中使用分段上传。

第一个功能

test = () => {
 fetch(url, {
   method: 'POST',
   headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json', //putting multipart/form-data doesn't work as well
  },
   body: JSON.stringify({
     username: 'abc',
   }),
 })
 .then((response) => console.log('fetchResponse', response))
 .catch((error) => {
   console.error('fetchError', error);
 });
}

第二个功能

test = () => {
 let data = new FormData();
 data.append("username", "abc");

 fetch(url, {
   method: 'POST',
   headers: {
      Accept: 'application/json',
      'Content-Type': 'multipart/form-data',
    },
   body: data,
 })
 .then((response) => console.log('fetchResponse', response))
 .catch((error) => {
   console.error('fetchError', error);
 });
}

服务器端代码:

控制器

public function index_post(){
    $username = $this->post('username', TRUE, TRUE);


    $password = $this->post('password', TRUE, TRUE);

    $push_key = $this->post('push_key');

    $user = $this->login->checklogin($username, $password);

    if ($user['status']) {

        if(!$user['customer']->model_image){
            $user['customer']->model_image='';
        }
        if(!$user['customer']->car_image){
            $user['customer']->car_image='';
        }
        return $this->responsedata($user['customer']);
    } else {
        return $this->responseerror($user['msg']);
    }

}

型号

public function checkLogin($username, $password){
    $where= "((`password` ='".md5($password)."') or (`p_reset_code` = '".$password."'))";
    $data = array();
    $username = str_replace(' ', '', strtolower($username));
    $this->db->where('username', $username);
    $this->db->where($where);

    $user = $this->db->get('tbl_appusers');

    if ($user->num_rows() > 0) {
        if (!$user->row()->is_logged_in) {
            if($password == $user->row()->p_reset_code){

                            if($user->row()->p_reset_date == date('Y-m-d')){
                                $no= strval($user->row()->p_reset_no);
                            }else{
                                $no = '0';
                            }
                            $newpassword=$user->row()->temp_password;
                        $arr=array('is_logged_in'=>0,
                                'p_reset_code'=>'',
                                 'p_reset_no'=>$no,
                                'temp_password'=>'',
                                'password'=>$newpassword
                            );

                        sendmail_password_reset_success($user->row()->email);

                        }else{
                            $arr= array('is_logged_in'=>0);
                        }
            $this->db->where('customer_id', $user->row()->customer_id)->update('tbl_appusers', $arr);
            $customer = $this->db
                ->select('tbl_customers.customer_id,tbl_customers.email, tbl_customers.salesdate, tbl_customers.name, tbl_customers.address, tbl_customers.cellphone, tbl_customers.scheme, tbl_customers.vcn, tbl_customers.ven, tbl_customers.model, tbl_customers.varient, tbl_customers.vehicleid, tbl_customers.color, tbl_customers.registrationno,tbl_customers.profile_image')
                tbl_customers.scheme, tbl_customers.vcn, tbl_customers.ven, tbl_customers.vehicleid,tbl_customers.model, tbl_customers.varient, tbl_customers.color, tbl_customers.registrationno,tbl_customers.profile_image')
                ->join('tbl_appusers', 'tbl_appusers.customer_id=tbl_customers.customer_id')
                ->join('tbl_model_images', 'tbl_model_images.model=tbl_customers.model', LEFT)
                ->where('tbl_customers.customer_id', $user->row()->customer_id)
                ->get('tbl_customers')->row();


                $this->db = $this->load->database('db2', true);
                $arra=array('vehicleid'=>$customer->vehicleid);
                $this->db->select('model_image, car_image')->from('mtable_vehicles')->where($arra);

                $vehicles = $this->db->get()->row();

                $customer->model_image=@$vehicles->model_image;
                $customer->car_image=@$vehicles->car_image;

            $data['status'] = true;
            if(!$customer->profile_image){$customer->profile_image='';}
            $data['customer'] = $customer;
        } else {
            $data['status'] = false;
            $data['msg'] = "Already logged in";
        }
    } else {
        $data['status'] = false;
        $data['msg'] = "username and password does not match in our system please try again";
    }
    return $data;
}

我在控制台中收到以下响应

fetchResponse

{data: {…}, status: 200, statusText: undefined, headers: {…}, config: {…}, …}
config
:
{transformRequest: {…}, transformResponse: {…}, timeout: 0, xsrfCookieName: "XSRF-TOKEN", adapter: ƒ, …}
data
:
{status: false, data: "username is required"}
headers
:
{transfer-encoding: "chunked", connection: "Keep-Alive", content-type: "application/json", set-cookie: Array(1), server: "Apache", …}
request
:
XMLHttpRequest {UNSENT: 0, OPENED: 1, HEADERS_RECEIVED: 2, LOADING: 3, DONE: 4, …}
status
:
200
statusText
:
undefined
__proto__
:
Object

【问题讨论】:

  • 我猜这就是您在后端处理数据的方式。两者都应该使用正确的后端实现。你也可以提供你的后端实现吗?
  • 您是在服务器端还是客户端出现错误?
  • @oma 服务器端在 Code Igniter 中编码。我对CI知之甚少。请看上面的服务器端代码。
  • @MohamedSameer 错误在客户端。如果我测试 api,它工作正常。虽然我注意到如果我在“用户名”键的前面或后面放置空格,但在测试时会出现同样的错误。
  • @AmritaStha - 您遇到的错误是什么?你要返回什么状态码?

标签: react-native


【解决方案1】:

我也不是 CodeIgniter 专家,但由于请求看起来不错 IMO,我想知道后端是否尝试以正确的方式访问变量。

查看 CI 文档,$this->input->post(.... 将是正确的调用,而不是 $this->post(...

https://www.codeigniter.com/user_guide/libraries/input.html#CI_Input::post

这可能是后端没有检测到用户名的原因吗?

一般来说,我建议使用断点调试后端,以确保所有预期数据都到达并且您以正确的方式处理它。

【讨论】:

    【解决方案2】:

    我记得我在与之交互的 PHP API 上遇到过类似的问题。

    我知道这听起来有点疯狂,但你能试试这个吗:

    test = () => {
     fetch(url, {
       method: 'POST',
       headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json', //putting multipart/form-data doesn't work as well
      },
       body: "?username=abc"
     })
     .then((response) => console.log('fetchResponse', response))
     .catch((error) => {
       console.error('fetchError', error);
     });
    }
    

    您应该能够查看您的 API 是否随后接受此操作。

    【讨论】:

    • 您是否只更改了 - 正文:“?username=abc”。这是什么意思?
    猜你喜欢
    • 1970-01-01
    • 2022-11-11
    • 2018-03-03
    • 2016-07-20
    • 2018-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多