gpt4 book ai didi

javascript - 使用 Axios 将对象从 React.js 发布到 PHP

转载 作者:行者123 更新时间:2023-12-05 02:56:09 26 4
gpt4 key购买 nike

我正在尝试使用 React JS 作为前端并使用 PHP 作为后端来创建一个登录表单。我似乎无法弄清楚如何将表单的数据(电子邮件和密码)传递给 PHP 脚本。我尝试使用谷歌搜索,但所有解决方案要么对我不起作用,要么没有数据。我正在使用 React v16。

这是我的前端代码:

import React, { useState } from 'react';

// libraries
import { Col,
Button,
Form,
FormGroup,
Label,
Input} from 'reactstrap';
import Axios from 'axios'


const App = () => {

const [email, setEmail] = useState('')
const [password, setPassword] = useState('')

const submit = () => {
Axios({
method: 'POST',
url: 'http://localhost:80/api/login.php',
headers: {
'Content-Type': 'application/json',
},
data: {
email,
password
}
})
.then((response) => {
console.log(response)
})
.catch((error) => {
console.log(error)
})
}

return (
<div>

<Form>
<FormGroup row>
<Label for="exampleEmail" sm={2}>Email</Label>
<Col sm={10}>
<Input value={email} onChange={e => setEmail(e.target.value)} type="email" name="email" placeholder="email" />
</Col>
</FormGroup>

<FormGroup row>
<Label for="examplePassword" sm={2}>Password</Label>
<Col sm={10}>
<Input value={password} onChange={e => setPassword(e.target.value)} type="password" name="password" placeholder="password" />
</Col>
</FormGroup>

<FormGroup check row>
<Col sm={{ size: 10, offset: 2 }}>
<Button onClick={submit}>Submit</Button>
</Col>
</FormGroup>
</Form>

</div>
);
}

export default App;

这是我的后端:

<?php

$data = json_decode(file_get_contents("php://input"));
echo "received data";
print_r("$data");

?>

现在,如果我查看 Chrome 检查器,它会说 Request Payload is {email: "xxx", password: "xxx"} 所以我知道我的前端正在尝试发送数据到 login.php 但我不知道如何用 PHP 来“捕获”前端发送的数据。

我打算做的是:一旦 login.php 获取数据,它将返回数据的 JSON 对象和字符串 "received data" 返回前端。

请帮我看看这个。我做了一整天的研究,但仍然找不到解决方案。

仅供引用,我一直在尝试我可以在网上找到的所有解决方案,例如我试过这个:

let data = {
email,
password
}

let form = new FormData()
form.append('data', data)

Axios.post('http://localhost:80/api/login.php', form)
.then(...)
.catch(...)

后端将是:

$email = $_POST['email'];
$password = $_POST['password'];

但是没有用。

最佳答案

您好,请替换您的 Php 代码,希望您能得到回复。

谢谢

<php
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: Content-Disposition, Content-Type, Content-Length, Accept-Encoding");
header("Content-type:application/json");
$data = json_decode(file_get_contents("php://input"));
echo "received data";
print_r($data);
?>

关于javascript - 使用 Axios 将对象从 React.js 发布到 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60774490/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com