大家好,我正在尝试开发一个android应用程序。
我尝试使用axios通过php将应用程序连接到远程mysql服务器(当我在web上使用vuejs运行代码时,它可以工作)。
以下是Vue原生代码;
fetchAllData:function(){
axios.post('db.php', {
action:'fetchall'
}).then(function(response){
app.allData = response.data;
});下面是db.php文件:
$received_data = json_decode(file_get_contents("php://input"));
$data = array();
if($received_data->action == 'fetchall')
{
$query = "
SELECT * FROM users ";
$statement = $connect->prepare($query);
$statement->execute();
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
$data[] = $row;
}
echo json_encode($data);
}下面是错误:
发布于 2020-10-20 21:29:05
您遇到的错误是网络错误,表示您没有internet连接或终结点无法访问。
您是否正在尝试连接到有效的终结点?
您可以在axios中设置端点,如下所示:
export const apiParams = {
baseURL: 'YOUR URL HERE',
timeout: 20000,
withCredentials: true
}
const api = axios.create(apiParams)导出后,您可以轻松地使用
api.post('db.php', { data });基本上,未处理的promise rejection意味着axios.post是一个promise,如果它被拒绝,您应该处理它的错误。
尝试将axios.post放在Try catch块中,您可以像这样使用ES6 async/await:
methods: {
async fetchAllData() {
try {
await axios.post('db.php', {
action: 'fetchall'
})
app.allData = response.data
} catch (error) {
console.log(error)
}
}
},或者你可以使用老式的方法来处理错误,但我不推荐使用它,如果你有一系列的承诺,最好像上面的例子那样使用async/await。
methods: {
fetchAllData() {
axios
.post('db.php', {
action: 'fetchall'
})
.then(function(response) {
app.allData = response.data
})
.catch(err => {
console.log(err)
})
}
},阅读有关使用then/catch https://javascript.info/promise-error-handling Async await处理promise的信息:https://javascript.info/async-await
在您解决网络错误之前,promise rejection应该会消失,但您的控制台日志中会有一个已处理的错误。
https://stackoverflow.com/questions/64444343
复制相似问题