我已经构建了一个后端,它使用PHP和MySQLi从数据库中插入和读取内容。我已经将PHP设置为REST API端点,并且可以使用Postman正确地GET和POST。我正在尝试创建一个客户端端点来发送API请求,但不知道如何正确地将Postman的代码集成到客户端。
这是要从数据库获取的服务器端端点:
<?php
include_once('config.php');
$task = isset($_GET['task']) ? mysqli_real_escape_string($conn, $_GET['task']) : "";
$sql = "SELECT * FROM `my_to_do_db`.`my_to_do_tb` WHERE task='{$task}';";
$get_data_query = mysqli_query($conn, $sql) or die(mysqli_error($conn));
if(mysqli_num_rows($get_data_query)!=0){
$result = array();
while($r = mysqli_fetch_array($get_data_query)){
extract($r);
$result[] = array("Task" => $task, "Date" => $date, 'Priority' => $priority);
}
$json = array("status" => 1, "info" => $result);
}
else{
$json = array("status" => 0, "error" => "To-Do not found!");
}
@mysqli_close($conn);
// Set Content-type to JSON
header('Content-type: application/json');
echo json_encode($json);
字符串
当我和 Postman 在一起时,它工作正常。下面是Postman在我点击“code”(JavaScript fetch)时导出的代码:
var urlencoded = new URLSearchParams();
var requestOptions = {
method: 'GET',
body: urlencoded,
redirect: 'follow'
};
fetch("http://localhost/endPointTest/info.php?task=Build API CRUD app", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
型
以下是我一直试图将它集成到客户端页面中的方法:
<!DOCTYPE html>
<html>
<head>
<title>Get Info API client side</title>
</head>
<body>
<h3 class="displayData"></h3>
<button type="submit" id="getData">Submit</button>
<script type="text/javascript">
const displayData = document.querySelector('.displayData')
document.getElementById('getData').addEventListener
('click', getData);
var urlencoded = new URLSearchParams();
var requestOptions = {
method: 'GET',
body: urlencoded,
redirect: 'follow'
};
function getData(){
fetch("http://localhost/endPointTest/info.php?task=Do some stuff", requestOptions)
.then(response => {
return response.json()
})
.then(data => {
console.log(data)
displayData.innerHTML = data
})
}
</script>
</body>
</html>
型
我的问题基本上是:如何将Postman中的代码集成到真实的世界的页面中?
1条答案
按热度按时间inkz8wg91#
事实证明,问题是Postman是用于测试的,并不像浏览器那样工作。CORS不是Postman的问题,但它是一个浏览器,在我添加所需的头到PHP页面的API能够连接。