使用fetch时没有数据,并尝试使用PHP返回它们

huangapple go评论83阅读模式
英文:

No data when using fetch and trying to return them with PHP

问题

I'm actually struggling on the following:
我实际上遇到了以下问题:

I'd like to send my form datas from JS to PHP. I'm then using Fetch.
我想从JS将表单数据发送到PHP。然后我使用Fetch。

Following you'll be able to look at my code. I tried both formData and json.stringify(object) as body. I also tried every content type possible. Didn't work neither. Tried $_POST as well instead of $post in PHP.
接下来,你可以查看我的代码。我尝试了formData和json.stringify(object)作为请求体。我还尝试了所有可能的内容类型。都没有起作用。在PHP中也尝试了$_POST而不是$post。

EDIT: I also tried if there were no redirections or anything else like this using curl.
编辑:我还尝试使用curl检查是否有重定向或类似的其他情况。

英文:

I'm actually struggling on the following:
I'd like to send my form datas from JS to PHP. I'm then using Fetch.

Following you'll be able to look at my code. I tried both formData and json.stringify(object) as body. I also tried every content type possible. Didn't work neither. Tried $_POST as well instead of $post in PHP.

import React from 'react';

class Test extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            username: "",
            password: ""
        };
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChange(input) {
        if(input.target.type === "text") {
            this.setState({username: input.target.value});
        } else {
            this.setState({password: input.target.value});
        }
    }

    handleSubmit(input) {
        input.preventDefault();
        const formData = new FormData();
        formData.append("username", this.state.username);
        formData.append("password", this.state.password);
        fetch("http://192.168.1.54/test/index.php", {
            method: 'POST',
            headers: {
                //"Content-Type": "application/x-www-form-urlencoded",
                "Content-Type": "multipart/form-data",
                Accept: "*",
                "Access-Control-Allow-Origin": "*",
                body: formData
            }
        }).then((r) => {
            if(r.ok) {
                r.json().then((r) => {
                    console.log(r);
                });
            }
            else {
                console.log(r);
            }
        });
    }

    render() {
        return(
            <form>
                <input type="text" name="username" value={this.state.username} onChange={this.handleChange} />
                <input type="password" name="password" value={this.state.password} onChange={this.handleChange} />
                <input type="submit" value="submit" onClick={this.handleSubmit} />
            </form>
        )
    }

}

export default Test;

PHP:

<?php

	header('Access-Control-Allow-Headers: *');
	header('Access-Control-Allow-Origin: *');

	$post = json_decode(file_get_contents('php://input'), true);
	$user->username = $post['username'];
	echo json_encode($user);
	
?>

OUTPUT:
{"username":null}

Thanks by advance for your help, spent the whole day on this...

EDIT: I also tried if there were no redirections or anything else like this using curl.

答案1

得分: 2

尝试使用 Content-Type 标头设置为 application/x-www-form-urlencoded 并将表单数据发送为 URL 编码字符串

handleSubmit(event) {
  event.preventDefault();
  const formData = new URLSearchParams();
  formData.append("username", this.state.username);
  formData.append("password", this.state.password);
  fetch("http://192.168.1.54/test/index.php", {
    method: 'POST',
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
    },
    body: formData.toString()
  })
  .then((response) => {
    if (response.ok) {
      return response.json();
    } else {
      throw new Error("Error: " + response.status);
    }
  })
  .then((data) => {
    console.log(data);
  })
  .catch((error) => {
    console.error(error);
  });
}

在您的 PHP 脚本中,您试图解码 JSON 数据,但实际上您正在发送 URL 编码的表单数据。而不是使用 json_decode,您应该使用 $_POST 直接访问表单数据。

<?php
header('Access-Control-Allow-Headers: *');
header('Access-Control-Allow-Origin: *');

$user = new stdClass();
$user->username = $_POST['username'];
echo json_encode($user);
?>
英文:

try to use the Content-Type header as application/x-www-form-urlencoded and send the form data as a URL-encoded string.

handleSubmit(event) {
  event.preventDefault();
  const formData = new URLSearchParams();
  formData.append(&quot;username&quot;, this.state.username);
  formData.append(&quot;password&quot;, this.state.password);
  fetch(&quot;http://192.168.1.54/test/index.php&quot;, {
    method: &#39;POST&#39;,
    headers: {
      &quot;Content-Type&quot;: &quot;application/x-www-form-urlencoded&quot;,
    },
    body: formData.toString()
  })
  .then((response) =&gt; {
    if (response.ok) {
      return response.json();
    } else {
      throw new Error(&quot;Error: &quot; + response.status);
    }
  })
  .then((data) =&gt; {
    console.log(data);
  })
  .catch((error) =&gt; {
    console.error(error);
  });
}

In your PHP script, you're trying to decode the JSON data, but you're actually sending form data as URL-encoded. Instead of using json_decode, you should use $_POST to access the form data directly.

&lt;?php
header(&#39;Access-Control-Allow-Headers: *&#39;);
header(&#39;Access-Control-Allow-Origin: *&#39;);

$user = new stdClass();
$user-&gt;username = $_POST[&#39;username&#39;];
echo json_encode($user);
?&gt;

huangapple
  • 本文由 发表于 2023年6月12日 07:47:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76452939.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定