我正在使用React组件中的fetch进行请求。对于绝大多数用户来说,它工作得很好,但有一位用户报告了以下错误:
Failed to load resource: net::ERR_EMPTY_RESPONSE
TypeError: Failed to fetch
不过,看起来类似的请求也在为他们工作。这来自Edge,但他们说Chrome也有同样的问题。
这是一个同源请求,所以我确信它不会是CORS问题。这种情况会不会是由广告拦截程序或防火墙设置引起的?
生成获取请求的代码(可能不相关):
function fetchWrapper(url, data, options, noModals) {
var body;
if (data instanceof FormData) {
body = data;
} elseif (data !== null) {
body = JSON.stringify(data);
}
options.body = body;
if (!options.method) {
options.method = "POST";
}
return fetch(url, options).then(response => {
if (!response.ok) {
return response.json().then(json => {
var error = (json && json.error) || response.statusText;
var message = "";
if (json.error && errors[json.error]) {
error = errors[json.error];
}
if (json.error && messages[json.error]) {
message = messages[json.error];
}
// Bad request - show the error message to the user
if (response.status >= 400 && response.status < 500) {
return handleError(noModals, error, message);
} else { // server error
error = errors.wrong;
message = messages.wrong;
return handleError(noModals, error, message, json ? json.error : "Unknown error");
}
})
}
return response.json().then(json => {
// the response returned a success code but there is an error message
if (json.error) {
return handleError(noModals, json.error);
}
return json;
});
}).catch(reason => { // JavaScript or network error
console.log(reason); // this is where the TypeError is printed
// not showing an error to the user
});
}
至于服务器代码,它是一个PHP后端,但我看不出有任何理由它会返回一个空响应。即使作为该用户登录并重复他们的操作,我也无法重现该问题。
发布于 2021-06-02 00:12:02
您可以尝试使用名为axios
的npm包。使用这个包,您可以轻松地创建一个请求。
import axios from 'axios';
const response = axios.get('[url]');
只需将ulr替换为您想要请求的url,数据将存储在response变量中。
如果这不起作用,您可以尝试使用await axios
进行异步请求。
https://stackoverflow.com/questions/67792313
复制相似问题