I am getting post response in network tab but still shows error in console

Viewed 2190

I am writing a post method in angular to post some data I am returning JSON in Codeigniter.

this is service:

public userlogin(data) {
  let uploadURL = `myurl`;

  const requestOptions: Object = {
    responseType: 'json'
  }    
   return this.http.post<any>(uploadURL, data,requestOptions).pipe(map((responce) => {
    console.log(responce);
    return responce;
  })
  );
}

In my component:

this.services.postuser(formData).subscribe(
  (data) => {
    console.log(data);
  }
);

following error, I am getting in the console Http error response to my post method

and here is a screenshot to my network tab where the response is JSON enter image description here

I have gone through a lot of stack overflow questions and answers but the solution is not working for me. I also changed post method response from JSON to text and response type in post method to text still receiving the same error.

backend function for post:

public function user_login()
    {
    if(is_array($_POST) && sizeof($_POST) >0){

       $where_array = array(
        'username'=>$this->input->post('username'),
        'password'=>$this->input->post('password')
        );

            $result = $this->Admin_model->checkuser($where_array);
            // print_r($result); die;
            if($result == "user not found" || $result == "incorrect password")
            {
                $json_data = array("Code"=>"1","data"=>$result);
                echo json_encode($json_data, JSON_UNESCAPED_SLASHES);

            }else{
                 $json_data = array("Code"=>"0","data" => "Login successfull");
                 echo json_encode($json_data, JSON_UNESCAPED_SLASHES);
            }
     }   
 }
3 Answers

solved by myself:

I found the issue was not about the request I was sending or the response. actually, it was a cors error because the server does not set to accept the cross-origin request.

first, I install this Firefox extension to test the problem then i got the response.

so After testing,In my ci file I set the origin to '*' to allow all origin.

header("Access-Control-Allow-Origin: *");

In my personal experience working with asp.net core backend (sql database) and NodeJS express backend (mongoDB)

inside Angular Front-end :

inside my services that return Observable simply return post request , like this :

return this.http.post(url, data, options);

in the component that use the service going to be like this :

this.service.postMethod(data).subscribe((res)=>{}, (err)=>{});

Also set content type json so it would not throw any other error just to be sure.

put below code on top of the php file:

header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');

For refer this answer.

Related