Can't access fetch post data in controller: Codeigniter

孤街醉人 提交于 2021-01-27 20:28:15

问题


I'm making a post request using fetch in my codeigniter project. The request looks like this

fetch('myurl/mycontroller', {
    method: 'POST',
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify({
         testdata: 123,
    })
 }).then((res) => {
    console.log(res);
 }).catch(console.log);

My controller looks like below

class MyController extends CI_Controller
{
    public function mycontroller()
    {
        $data = $this->input->post('testdata');
        return $data . " is the passed data.";
    }
}

But the data isn't getting passed to my controller. I echoed out $_POST and it gave me an empty array. Any idea what I'm doing wrong? I'm using codeigniter 2 (which I know is very old now)


回答1:


So not completely sure about the actual reason but there might be some bug with the CI core of codeigniter which doesn't parse the data passed to controller using fetch. Using FormData() and axios I was able to resolve the issue.

 var postData = new FormData();
 postData.append('testdata', 123);
 axios.post('myurl/mycontroller', postData).then(function(response){
     console.log("success:", response);
 }).catch(function(error){
     console.log("error:", error);
 });



回答2:


Use FormData() to submit it

var postData = new FormData();
postData.append('testdata', 123);

fetch('myurl/mycontroller', {
    method: 'POST',
    headers: {
        "Content-Type": "application/json"
    },
    body: postData
 }).then((res) => {
    console.log(res);
 }).catch(console.log);



回答3:


This worked for me:

let postData = new FormData();
postData.append('testdata', 123);

fetch('myurl/mycontroller', {
    method: 'POST',
    mode: 'no-cors',
    headers: {
        "Content-Type": "application/json"
    },
    body: postData
 }).then((res) => {
    console.log(res);
 }).catch(console.log);

Use formData and mode: 'no-cors' in fetch settings.



来源:https://stackoverflow.com/questions/64126824/cant-access-fetch-post-data-in-controller-codeigniter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!