【问题标题】:ReactJS axios POST request send all options as a single JSON key with empty valueReactJS axios POST 请求将所有选项作为具有空值的单个 JSON 键发送
【发布时间】:2021-01-23 11:18:50
【问题描述】:

我在前端使用 ReactJS 并向 CodeIgniter4 后端发出 POST 请求。

我的前端调用看起来像这样 -

axios.post('http://localhost/exampleApiEndpoint', { sample_key: 'sample_value' })
    .then(response => {
        // Do something
    })

如果我运行以下代码 -

$this->request->getPost('sample_key');

我希望它返回 'sample_value' 但我得到 null


所以我决定在 CI4 中运行以下代码,看看后台发生了什么

$this->request->getRawInput()

它返回{{"hello":"world"}: ""}

果然,当我运行$this->request->getPost('{"hello":"world"}'); 时,它给了我空字符串(没有空,但空字符串)

我对这两个框架都是新手。我不完全确定如何从这一点进一步推进。 我使用以下 sn-p 作为解决方法,只要输入中没有符号就可以使用。如果有,它们将转换为下划线。这不太理想。

$raw_input = $this->request->getRawInput();
$json_input = json_decode(array_key_first($raw_input));

【问题讨论】:

    标签: php reactjs ionic-framework axios codeigniter-4


    【解决方案1】:

    Axios 在将数据发送到 API 的同时,以 JSON Body 的格式发送数据。为了让您以 POST 的形式发送数据,您必须使用 FormData API。

    let formData = new FormData();
    formData.append('sample_key','sample_value');
    

    发送这个 FormData 对象而不是您发送的 Javascript 对象:

    axios.post('http://localhost/exampleApiEndpoint', formData)
        .then(response => {
            // Do something
        })
    

    在 CI4 控制器中,您可以通过以下方式获取数据:

    $data = $this->request->getPost();
    

    参考:https://developer.mozilla.org/en-US/docs/Web/API/FormData

    【讨论】:

    • 感谢您的解决方案。这对我有用。虽然我仍然更喜欢以 json 格式发送数据。但这同样有效:)
    • 是的,这样更方便,但是没有办法通过直接传递 JSON 来发布数据(至少据我所知)。
    【解决方案2】:

    axios client is posting the request with Content-Type header of application/json 并作为 JSON 有效负载的原始输入流。

    使用CodeIgniter\HTTP\IncomingRequest::getJSON 从请求正文中获取此流,并将其作为JSON 解析为对象。

    $json = $this->request->getJSON();
    
    // Access sample_key field from object
    $json->sample_key;
    

    您还可以通过将true 传递给第一个参数,将请求正文解析为关联数组。

    $json = $this->request->getJSON(true);
    
    // Access 'sample_key' key in array
    $json['sample_key'];
    

    【讨论】:

    • 我真的很喜欢这个解决方案。看起来很优雅,但它不适合我。 $this->request->getJSON(); 返回 null。
    • @AlienSteak 它应该返回发布的有效负载。我花了一些时间set up an experiment
    【解决方案3】:

    以这种方式使您成为数据对象,然后将此对象传递给发布请求。

    let data = {sample_key: "sample_value"}
    
    axios.post('http://localhost/exampleApiEndpoint', data)
    .then(response => {
        // Do something
    })
    

    谢谢

    【讨论】:

      猜你喜欢
      • 2020-10-17
      • 2021-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-29
      • 2019-05-27
      • 1970-01-01
      • 2015-10-09
      相关资源
      最近更新 更多