![](/img/trans.png)
[英]Request failed with status code 401 at createError "Unauthenticated"
[英]Request failed with status code 404 at createError
我正在尝试从表中获取数据,例如 API 和 AXIOS 到 React 前端。 我正在使用代理来获取数据,并且当文件位于远程服务器上时它工作正常( http://auto-parts.oaccoman.com/test.php )。 当我使用来自本地(http://localhost:81/data/index.php)的相同数据时,它会在控制台中显示错误。
Error: Request failed with status code 404
数据和表单.jsx
import React from 'react'
class DataandForm extends React.Component{
constructor()
{
super()
this.state={
row:[],
logged:true
}
}
componentDidMount()
{
const axios = require('axios');
const remote="http://auto-parts.oaccoman.com/test.php"
const proxy="https://cors-anywhere.herokuapp.com/"
const local="http://localhost:81/data/index.php"
axios
.get(proxy+local)
.then( response =>{
// handle success
console.log(response);
this.setState({row:response.data});
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
setTimeout(prests=>{
this.setState({
logged:false.logged
})
}, 2500);
}
render()
{
return(
<div className="container">
<div className="row">
{this.state.logged?'Loading Your Data...' : <div className="col-sm-6">
{this.state.row.map(datum=>
<div className="row">
<div className="col-sm-4">key={datum.id}</div>
<div className="col-sm-4">data1={datum.name}</div>
{/* <div className="col-sm-4">data2={datum.value}</div> */}
</div>
)}
</div>}
<div className="col-sm-10 offset-sm-2"><br/>
<form class="form-inline" action=" " method="post" >
<div class="form-group">
<label for="email">FIRSTNAME:</label>
<input type="text" name="data1" class="form-control" id="email" />
</div>
<div class="form-group">
<label for="pwd">LASTNAME:</label>
<input type="text" name="data2" class="form-control" id="pwd" />
</div>
<button type="submit" class="btn btn-danger">Submit</button>
</form>
</div>
</div>
</div>
)
}
}
export default DataandForm
http://localhost:81/data/index.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydata";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM datum";
$result = $conn->query($sql);
$jsonarray= [];
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$jsonarray[]=$row;
}
} else {
echo "0 results";
}
echo json_encode($jsonarray);
?>
如果不需要从 localhost 访问代理(并且您知道为什么需要这样做),我想您可以确定您是在本地运行还是在远程服务器中运行(通过某种配置)然后运行一些东西与此类似:
let url
const proxy="https://cors-anywhere.herokuapp.com/"
const local="http://localhost:81/data/index.php"
if (runningLocally) // usually some way to determine a "development mode"
url = local
else
url = proxy + local
(这可以写得更短,我这样做只是为了清楚)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.