我在网络选项卡中收到 post 响应,但在控制台中仍然显示错误

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

我正在 angular 中编写一个 post 方法到 post 我在 Codeigniter 中返回 JSON 的一些数据。

这是服务:

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;
  })
  );
}

在我的组件中:

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

出现以下错误,我正在进入控制台

这是我的网络选项卡的屏幕截图,其中的响应是 JSON

我经历了很多堆栈溢出问题和答案,但解决方案对我不起作用。 我还将 post 方法响应从 JSON 更改为文本,并将 post 方法中的响应类型更改为文本仍然收到相同的错误。

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);
            }
     }   
 }

根据我使用 asp.net 核心后端(sql 数据库)和 NodeJS Express 后端(mongoDB)

的个人经验

里面 Angular Front-end :

在我的服务中 return Observable 只需 return post 请求,就像这样:

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

在使用该服务的组件中将是这样的:

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

自己解决:

我发现问题与我发送的请求或响应无关。 实际上,这是一个 cors 错误,因为服务器没有设置为接受 cross-origin 请求。

首先,我安装 this Firefox 扩展来测试问题,然后我得到了响应。

所以经过测试,在我的 ci 文件中,我将原点设置为 '*' 以允许所有原点。

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

同时设置内容类型 json 这样它就不会抛出任何其他错误只是为了确定。

将下面的代码放在 php 文件的顶部:

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

参考这个answer.