React调用Node服务器无响应:请求成功却无返回内容
问题分析与解决方案
服务端代码问题
你的Node.js服务端代码没有正确发送响应。Express的res对象不能直接通过赋值status和data来返回内容,必须使用Express提供的响应方法完成响应发送。
修正后的服务端代码
如果返回纯文本:
export const getTopMovies = async (req, res) => { console.log("Inside Server") res.status(200).send("movies"); }
如果返回JSON格式(更适配前后端交互场景):
export const getTopMovies = async (req, res) => { console.log("Inside Server") res.status(200).json({ data: "movies" }); }
客户端代码问题
客户端的响应处理逻辑需要和服务端的返回格式匹配:
- 若服务端返回纯文本,需用
response.text()替代response.json(),否则会触发JSON解析错误 - 若服务端返回JSON,可继续使用
response.json(),但要确保打印的字段与返回结构一致
对应修正后的客户端代码
情况1:服务端返回纯文本时
import { useEffect } from 'react'; const TopMovies = () => { useEffect(() => { fetch('http://localhost:8000/movies/getTopMovies') .then(response => response.text()) .then(data => console.log(data)) }, []) return ( <div className="max-h-screen w-full fixed h-screen bg-BGColor pt-6"> <h1 className="text-zinc-50 pt-4 pl-10 text-2xl ">Top Movies</h1> <div className="min-w-[82.5%] absolute min-h-[78%] mt-6 ml-10 rounded-3xl bg-BGColorLight1 text-white"> </div> </div> ) } export default TopMovies
情况2:服务端返回JSON时
import { useEffect } from 'react'; const TopMovies = () => { useEffect(() => { fetch('http://localhost:8000/movies/getTopMovies') .then(response => response.json()) .then(data => console.log(data.data)) }, []) return ( <div className="max-h-screen w-full fixed h-screen bg-BGColor pt-6"> <h1 className="text-zinc-50 pt-4 pl-10 text-2xl ">Top Movies</h1> <div className="min-w-[82.5%] absolute min-h-[78%] mt-6 ml-10 rounded-3xl bg-BGColorLight1 text-white"> </div> </div> ) } export default TopMovies
额外提示:React组件名需首字母大写(如TopMovies而非topMovies),这是React的规范要求。
内容的提问来源于stack exchange,提问作者Niroyo
相关产品推荐
相关产品推荐

