无法访问控制器中的提取 post 数据:Codeigniter

Can't access fetch post data in controller: Codeigniter

我正在我的 codeigniter 项目中使用 fetch 发出 post 请求。请求看起来像这样

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(我知道它现在已经很旧了)

使用FormData()提交

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

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

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

这对我有用:

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

在获取设置中使用 formDatamode: 'no-cors'

我遇到了类似的问题,后来我在没有改变 js fetch 的情况下修复了它。 这是我解决它的方法。

  • 确保你的路由文件中有一个 Post 路由到你的 CI 控制器
  • 确保您的提取 api url 没有尾随的 '/'
let data = await fetch('https://example.com/api/login', {
              method: 'POST',
              credentials: 'same-origin',
              mode: 'same-origin',
              headers: {
                'Accept':       'application/json',
                'Content-Type': 'application/json',

              },
              body: JSON.stringify({email: 'sample@gmail.com', password: 'crypt887faked'}),
          });

          let response = await data.json();

这对我有用。我希望它也适用于某些人。