React中Fetch请求返回200却无法获取文本内容的问题
解决Fetch请求无法获取响应内容的问题
问题根源
- 第一个
then未返回Promise:response.text()会返回一个Promise对象,但你的回调函数里没有用return把它传递下去,导致后续then接收不到解析后的文本,只能拿到undefined。 - 错误处理逻辑错误:你用第三个
then处理错误,但fetch的请求错误不会进入then的第三个参数,只有Promise被拒绝时才会触发catch,所以这个then的error参数也是undefined,这就是控制台两次输出undefined的原因。
修正后的前端代码
fetch('http://localhost:80', { method: 'POST', headers: {'Accept': 'text/*'} }) .then((response) => { // 必须return这个Promise,让下一个then拿到解析后的文本内容 return response.text(); }) .then((msg) => { console.log(msg); // 这里会正常输出"Hello World!" }) .catch((error) => { console.error('请求出错:', error); });
PHP端优化建议
虽然当前脚本已经执行,但可以补充两个细节让代码更规范:
<?php header('Access-Control-Allow-Origin: http://localhost:3000'); // 明确设置响应的文本类型,避免前端解析异常 header('Content-Type: text/plain; charset=utf-8'); $FILE = fopen("test.txt", "w"); fwrite($FILE, "Hello World"); fclose($FILE); // 记得关闭文件句柄,避免资源泄漏 ?> Hello World!
额外补充
如果需要处理HTTP状态码异常(比如404、500),可以在第一个then里增加判断:
.then((response) => { if (!response.ok) { throw new Error(`请求失败,状态码:${response.status}`); } return response.text(); })
内容的提问来源于stack exchange,提问作者infinitezero
相关产品推荐
相关产品推荐

