免责声明:我非常不熟悉PHP。我一直讨厌在其中工作,所以我从不费心去学习它。
我正在关注this教程,因为它准确地描述了我的工作(仅使用PHP与数据库进行接口的前端应用程序),并且遇到了一个非常奇怪的问题。
如果我输入错误的数据库密码,则会收到一条错误消息,提示TypeError: this.state.contacts.map is not a function
(联系人是我的变量)。这是非常可预期的,因为无法连接到数据库也意味着它将无法获取数据。
如果我输入正确,它将告诉我进行数据库登录的文件不存在! GET http://127.0.0.1:8080/api/contacts.php 404 (Not Found)
堆栈跟踪:
[Mon Jul 15 15:20:29 2019] 127.0.0.1:61859 [200]: /api/contacts.php
[Mon Jul 15 15:36:18 2019] 127.0.0.1:62737 [200]: /
[Mon Jul 15 15:36:20 2019] PHP Notice: Undefined index: PATH_INFO in C:\[...]\Desktop\php-react-rest-api-crud\api\contacts.php on line 11
[Mon Jul 15 15:36:20 2019] PHP Notice: Undefined index: id in C:\[...]\Desktop\php-react-rest-api-crud\api\contacts.php on line 21
[Mon Jul 15 15:36:20 2019] 127.0.0.1:62738 [404]: /api/contacts.php
第一次没问题,然后说它不存在。
完整代码here 注意:我知道这是不正确的代码,我只是想尝试一下如何构造我的项目。
<?php
$host = "localhost";
$user = "root";
$password = "password";
$dbname = "reactdb";
$id = '';
$con = mysqli_connect($host, $user, $password, $dbname);
$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'], '/'));
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
switch ($method) {
case 'GET':
$id = $_GET['id'];
$sql = "select * from contacts" . ($id ? " where id=$id" : '');
break;
case 'POST':
$name = $_POST["name"];
$email = $_POST["email"];
$city = $_POST["city"];
$contact = $_POST["contact"];
$sql = "insert into contacts (name, email, city, contact) values ('$name', '$email', '$city', '$contact')";
break;
}
// run SQL statement
$result = mysqli_query($con, $sql);
// die if SQL statement failed
if (!$result) {
http_response_code(404);
die(mysqli_error($con));
}
if ($method == 'GET') {
if (!$id) echo '[';
for ($i = 0; $i < mysqli_num_rows($result); $i++) {
echo ($i > 0 ? ',' : '') . json_encode(mysqli_fetch_object($result));
}
if (!$id) echo ']';
} elseif ($method == 'POST') {
echo json_encode($result);
} else {
echo mysqli_affected_rows($con);
}
$con->close();
编辑:我的问题与未定义的索引无关。问题与PHP无法识别已经使用的文件有关。
编辑2:这是创建我要询问的错误的index.php文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>PHP| MySQL | React.js | Axios Example</title>
<script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<!-- Load Babel Compiler -->
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id='root'></div>
<script type="text/babel">
class ContactForm extends React.Component {
state = {
name: '',
email: '',
contact: '',
city: '',
}
handleFormSubmit( event ) {
event.preventDefault();
let formData = new FormData();
formData.append('name', this.state.name)
formData.append('email', this.state.email)
formData.append('city', this.state.city)
formData.append('country', this.state.contact)
console.log("Trying to contact the API...");
axios({
method: 'post',
url: '/api/contacts.php',
data: formData,
config: { headers: {'Content-Type': 'multipart/form-data' }}
})
.then(function (response) {
//handle success
console.log(response)
})
.catch(function (response) {
//handle error
console.log(response)
});
}
render(){
return (
<form>
<label>Name</label>
<input type="text" name="name" value={this.state.name}
onChange={e => this.setState({ name: e.target.value })}/>
<label>Email</label>
<input type="email" name="email" value={this.state.email}
onChange={e => this.setState({ email: e.target.value })}/>
<label>Contact</label>
<input type="text" name="contact" value={this.state.contact}
onChange={e => this.setState({ country: e.target.value })}/>
<label>City</label>
<input type="text" name="city" value={this.state.city}
onChange={e => this.setState({ city: e.target.value })}/>
<input type="submit" onClick={e => this.handleFormSubmit(e)} value="Create Contact" />
</form>);
}
}
class App extends React.Component {
state = {
contacts: []
}
render() {
return (
<React.Fragment>
<h1>Contact Management</h1>
<table border='1' width='100%' >
<tr>
<th>Name</th>
<th>Email</th>
<th>Contact</th>
<th>City</th>
</tr>
{this.state.contacts.map((contact) => (
<tr>
<td>{ contact.name }</td>
<td>{ contact.email }</td>
<td>{ contact.contact }</td>
<td>{ contact.city }</td>
</tr>
))}
</table>
<ContactForm />
</React.Fragment>
);
}
componentDidMount() {
const url = '/api/contacts.php'
console.log("Trying to contact the API...");
axios.get(url).then(response => response.data)
.then((data) => {
this.setState({ contacts: data })
console.log(this.state.contacts)
})
}
}
ReactDOM.render(<App />, document.getElementById('root'));
</script>
</body>
</html>
数据库有1个表,其中包含4个字段:姓名,电子邮件,城市,联系方式。
答案 0 :(得分:1)
第一次没问题,然后说它不存在。
...
编辑:我的问题与未定义的索引无关。问题与PHP无法识别已经使用的文件有关。
它确实存在。
两次都正确执行了代码,但是第二次,执行遵循以下路径:
if (!$result) {
http_response_code(404);
die(mysqli_error($con));
}
并返回404(您正在解释的404不存在)