创建 React 组件时,通过 axios 向服务器发出请求以获取视图数据,在我的情况下,它只是对附近文件夹中的 php 脚本的请求。问题是,由于某种未知的原因,请求在大约 80% 的情况下是成功的——数据到达并且一切正常,但有时,在等待一段时间后,会抛出关于 axios 超时到期的错误,即使它至少是 5/10/15/etc 秒,感觉它根本没有到达 php 脚本本身,在 php 方面,数据只是在到达路由时给出,它总是与下面描述的请求,没有复杂的计算,也没有睡眠。
更新。问题出在服务器端,通过postman模拟GET请求时响应太长,周期性返回空body,没有报错等。也许这是 PHP 或 Apache 设置中的内容?
Axios 设置
const api = axios.create({
baseURL: "/api/",
timeout: 1000 * 5,
withCredentials: true
});
要求
api.get(uri)
.then(responce => dispatch({ type: "received", payload: responce.data }))
.catch(error => dispatch({ type: "error", payload: error }))
向控制台输出错误时,只需编写:
error from server in action received: timeout of 5000ms exceeded
标题。
成功的:
General
Request URL: http://localhost:3000/api/category/phones
Request Method: GET
Status Code: 200 OK
Remote Address: 127.0.0.1:3000
Referrer Policy: strict-origin-when-cross-origin
Response Headers
connection: close
Content-Encoding: gzip
content-type: text/html; charset=UTF-8
transfer-encoding: chunked
Vary: Accept-Encoding
Request Headers
Accept: application/json, text/plain, */*
Cache-Control: no-cache
Connection: keep-alive
DNT: 1
Host: localhost:3000
Pragma: no-cache
Referer: http://localhost:3000/category/phones
X-KL-Ajax-Request: Ajax_Request
超时错误返回的那个
General
Request URL: http://localhost:3000/api/category/phones
Referrer Policy: strict-origin-when-cross-origin
Request Headers
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Cache-Control: no-cache
Connection: keep-alive
Host: localhost:3000
Pragma: no-cache
Referer: http://localhost:3000/category/phones
X-KL-Ajax-Request: Ajax_Request
PHP 脚本
if ($_SERVER["REQUEST_METHOD"] === "GET") {
$uri = trim(filter_var($_SERVER["REQUEST_URI"], FILTER_SANITIZE_URL));
print json_encode(Request::getCategoryData($uri, 5));
}
public static function getCategoryData($uri, $limit = null)
{
// тут я сократил, просто извлечение из uri подстроки для названия
// таблицы категории, типа phones/gadgets/etc
$category_products_table = $uri;
$products_query = $limit
? "SELECT * FROM {$category_products_table} LIMIT {$limit}"
: "SELECT * FROM {$category_products_table}";
$pdo = Connect::exec()->prepare($products_query);
$pdo->execute();
return $pdo->fetchAll();
}
问题出在卡巴斯基防病毒软件中,禁用它可以消除所有请求问题。经过三天的错误搜索、安装不同版本的 Apache 和 PHP、阅读日志直到凌晨五点,我可能会为自己订购一件 T 恤,上面写着“问题出在 Kaspersky Anti-Virus”。