React应用无法从Node.js服务器获取UND网站数据的问题咨询
问题原因及解决方案
核心问题点
- 端口冲突:React开发服务器默认端口为3000,与你的Node服务器端口重复,导致请求无法正常到达服务器。
- 响应格式错误:你将数组数据以
text/html类型返回,React无法正确解析该格式,且直接渲染数组会显示为逗号分隔的字符串。 - 跨域限制:React与Node服务器分属不同端口,浏览器的同源策略会拦截跨端口请求。
具体修复步骤
1. 调整Node服务器配置
首先安装跨域支持中间件:
npm install cors
修改Node服务器代码:
const express = require("express"); const cheerio = require("cheerio"); const axios = require("axios"); const cors = require("cors"); const app = express(); app.use(cors()); // 启用跨域支持 // 修改端口为3001,避免与React默认端口冲突 const PORT = process.env.PORT || 3001; const website = "https://und.com"; let options = { headers: { "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36" } }; app.get("/", (req, res) => { axios(website, options) .then(({ data }) => { const $ = cheerio.load(data); const result = $(".post__meta h3 a:last-child") .map((_, e) => $(e).text().trim()) .get(); console.log(result); // 以JSON格式返回数据,自动设置正确的Content-Type res.json(result); }) .catch((error) => { console.log("An error occurred:", error); res.status(500).json({ error: "抓取数据时发生错误" }); }); }); app.listen(PORT, () => { console.log(`server is running on PORT: ${PORT} `); });
2. 修正React应用代码
import React, { useEffect, useState } from "react"; import axios from "axios"; function Home() { const [headlines, setHeadlines] = useState([]); useEffect(() => { axios .get("http://localhost:3001") // 请求Node服务器的3001端口 .then((response) => { setHeadlines(response.data); }) .catch((error) => { console.log("An error occurred:", error); }); }, []); // 循环渲染每条头条内容 return ( <div> <h2>UND头条</h2> <ul> {headlines.map((headline, index) => ( <li key={index}>{headline}</li> ))} </ul> </div> ); } export default Home;
3. 启动顺序
- 先启动Node服务器:
node 你的服务器文件名.js - 再启动React应用:
npm start
内容的提问来源于stack exchange,提问作者rpuh
相关产品推荐
相关产品推荐

