无法在控制器中访问获取发布数据:Codeigniter [英] Can't access fetch post data in controller: Codeigniter

查看:22
本文介绍了无法在控制器中访问获取发布数据:Codeigniter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在我的 codeigniter 项目中使用 fetch 发出发布请求.请求如下所示

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

我的控制器如下所示

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

但是数据没有传递给我的控制器.我回显了 $_POST 它给了我一个空数组.知道我做错了什么吗?我正在使用 codeigniter 2(我知道它现在已经很老了)

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)

推荐答案

所以不完全确定实际原因,但可能存在一些错误,即 codeigniter 的 CI 核心没有解析使用 fetch 传递给控制器​​的数据.使用 FormData()axios 我能够解决问题.

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

这篇关于无法在控制器中访问获取发布数据:Codeigniter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆