我正在用 Angular 编写一个 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);
}
);
我经历了很多堆栈溢出问题和答案,但解决方案对我不起作用。 我还将 post 方法响应从 JSON 更改为文本,将 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);
}
}
}
最佳答案
自己解决了:
我发现问题与我发送的请求或响应无关。 实际上,这是一个cors错误,因为服务器没有设置接受跨域请求。
首先,我安装 this Firefox 扩展来测试问题,然后我得到了响应。
所以经过测试,在我的 ci 文件中我将原点设置为 '*' 以允许所有原点。
header("Access-Control-Allow-Origin: *");
关于angular - 我在网络选项卡中收到帖子响应,但在控制台中仍然显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56625871/