这是我第一次从Angular向CodeIgniter rest API发出post方法请求。
postUsertask(Userid,TaskName)
{
let body ={
userid:Userid, taskname:TaskName
};
console.log(body);
return this.http.post("http://localhost/ci-abc/api/add_task",JSON.stringify(body) )
.map(res => res.json());
}
codeigniter中的API方法:
function add_task_post()
{
$obj=json_decode(file_get_contents('php://input'));
$taskname = $obj->taskname;
$userid = $obj->userid;
if (!$taskname || !$userid) {
$this->response("Enter taskname and userid to add", 400);
} else
$result = $this->todo_model->add_task($taskname, $userid);
if ($result === 0) {
$this->response("Task could not be added. Try again.", 404);
} else {
$this->response("success", 200);
}
}
必须包含才能访问数据
$ OBJ = json_decode(的file_get_contents( 'PHP://输入'));
因为$ this-> input-> post和$ _POST为空,并且从angular收到的数据是一个对象,因此必须使用 - >进行访问。符号。我很好奇这不是正确和道德的方式来做到这一点。此外,当我没有放JSON.stringify时,它给了我Cross Origin Request阻止错误,这就是为什么我把它。我应该如何在angular4中使用angular4中的POST和PUT请求来停止API?
如何摆脱不允许我调用API方法的CORS错误,如果我可以摆脱CORS错误,那么我也可以删除JSON.stringify
,它会按原样发送数据而我相信应该通过input->post
或$_POST
访问数据。
编辑2: 在进行POST PUT和DELETE API调用时出现这些错误。
阻止跨源请求:同源策略禁止读取 http://localhost/ci-abc/api/del_task?taskid=34处的远程资源。 (原因:CORS预检频道没有成功)
答案 0 :(得分:1)
编辑(完美解决方案):
发现formdata对象方法已被弃用,因此我只在选项中包含了一个标头,并包含在API调用http.post方法中,该方法工作正常并且是更好的解决方案。
constructor(public http:Http) {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let options = new RequestOptions({ headers: headers });}
createUser(userName)
{
let body = { username:userName};
return this.http.post("http://localhost/ci-abc/api/create_user",body,this.options)
.map(res => res.json());
}
弃用的方法(工作但已弃用/非惯常做法):
花了几个小时但找到了解决方案,我创建了body作为一个新的formdata对象,将其作为键及其值附加参数,现在我正在通过$ this-> input-> post检索它。
let body = new FormData;
body.append('userid', Userid);
body.append('taskname', TaskName);
console.log(body);
return this.http.post("http://localhost/ci-abc/api/add_task",body)
.map(res => res.json());
在我的codeigniters API控制器
的构造函数中使用这些头文件header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Access-Control-Allow-Origin');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE');
API方法:
function add_task_post()
{
$userid = $this->input->post('userid');
$taskname = $this->input->post('taskname');
if (!$taskname || !$userid) {
$this->response("Enter taskname and userid to add", 400);
} else
$result = $this->todo_model->add_task($taskname, $userid);
if ($result === 0) {
$this->response("Task could not be added. Try again.", 404);
} else {
$this->response("success", 200);
}
}