在Angular 4调用的CodeIgniter API中,input-> post和$ _POST是空的,在angular 4中发出post请求的正确方法是什么
This is the first time I'm making a post method request from Angular to CodeIgniter rest API.
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());
}
API method in codeigniter:
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);
}
}
Had to include to access the data
$obj=json_decode(file_get_contents('php://input'));
Because the $this->input->post and $_POST were empty and the data recieved from angular was an object so had to be accessed with -> notation. I am curious that this is not the right and ethical way to do this. Also when I didn't put JSON.stringify it gave me Cross Origin Request blocked error so that's why I put it. How should I make POST and PUT request in angular4 to rest API in CodeIgniter?
How do I get rid of CORS error which doesn't let me call the API method, if I can get rid of CORS error then I could also remove JSON.stringify
which will send the data as it is and I believe the data should be accessed via input->post
or $_POST
.
EDIT 2: These sort of errors while making POST PUT and DELETE API call.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost/ci-abc/api/del_task?taskid=34. (Reason: CORS preflight channel did not succeed)
这是我第一次从Angular向CodeIgniter rest API发出post方法请求。 p>
postUsertask(Userid,TaskName)
{
let body = {
userid:Userid,taskname:TaskName
};
console.log(body);
返回this.http.post(“http:// localhost / ci-abc / api / add_task”,JSON.stringify(body))
.map(res => res.json());
}
code> pre>
codeigniter中的API方法: p>
function add_task_post()
{
$ obj = json_decode(file_get_contents('php:// input'));
$ taskname = $ obj-> taskname;
$ userid = $ obj-> userid;
if( !$ taskname ||!$ userid){
$ this-> response(“输入要添加的任务名和用户ID”,400);
}否则
$ result = $ this-> todo_model-&gt ; add_task($ taskname,$ userid);
if if($ result === 0){
$ this-> response(“无法添加任务。再试一次。”,404);
} else {
$ this-> response(“success”,200);
}
}
code> pre>
必须包含才能访问数据
$ obj = json_decode(file_get_contents('php:// input')); p>
blockquote>
因为 $ this-> input-> post和$ _POST为空,从angular收到的数据是一个对象 因此必须使用 - >进行访问 符号。 我很好奇这不是正确和道德的方式来做到这一点。 此外,当我没有放JSON.stringify时,它给了我Cross Origin Request阻止错误,这就是为什么我把它。 我应该如何在angular4中使用angular4中的POST和PUT请求来停止API? p>
如果我能得到的话,如何摆脱不允许我调用API方法的CORS错误 摆脱CORS错误然后我也可以删除 JSON.stringify code>,它将按原样发送数据,我相信数据应该通过 input-> post code>或 $ _ POST code>。 p>
编辑2:
进行POST PUT和DELETE API调用时出现的这类错误。 p>
阻止跨源请求:同源策略不允许在 http:// localhost / ci-abc / api / del_task?taskid = 34 。
(原因:CORS预检频道未成功) p>
blockquote>
div >
EDIT (Perfect Solution):
Found out that the formdata object approach was deprecated so I just included a header in options and included in the API call http.post method which works fine and is much better solution.
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());
}
Deprecated approach (Works but deprecated/not usual practice):
Took few hours but found the solution, I created body as a new formdata object, appended parameters to it as key and their values and it worked fine now I am retrieving through $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());
Using these headers in the constructor of my codeigniters API controller
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 method:
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);
}
}