我有一个使用 axios 的 React Native 项目,以及一个使用 Node.js 的服务器。我启动项目,转到所需的页面,出现错误 - 接收新闻时出错:AxiosError:网络错误。当我在浏览器中引用 localhost 运行index.html时,一切都很好,数据来了,没有错误,为什么会这样?
/news/index.tsx(参考server.js(节点))
import React, { useState, useEffect } from 'react';
import { View, Text, FlatList } from 'react-native';
import axios from 'axios';
import { Link } from "expo-router";
export default function NewsScreen(){
const [news, setNews] = useState([]);
useEffect(() => {
const fetchNews = async () => {
try {
const response = await axios.get('http://localhost:3000/news?category=business');
setNews(response.data.articles);
} catch (error) {
console.error('Error when receiving news:', error);
}
};
fetchNews();
}, []);
return (
<View>
<Link href="/signin">
<Text>Go to registration</Text>
</Link>
<FlatList
data={news}
keyExtractor={item => item.title}
renderItem={({ item }) => (
<View>
<Text>{item.title}</Text>
<Text>{item.description}</Text>
</View>
)}
/>
</View>
);
};
NewsScreen;
服务器.js(节点)
const express = require("express");
const cors = require("cors"); // Connecting the cors package
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json()); // Parsing the request body in JSON format
app.use(cors()); // Using cors middleware to allow all requests
// Handler for GET request to index2.html
app.get("/index2.html", (req, res) => {
res.sendFile(__dirname + "/index2.html");
});
// Handler for GET request to news
app.get("/news", async (req, res) => {
const { category } = req.query;
const apiKey = "cc6cda365d534d32afd2d4bfbdd671fa";
try {
const { default: fetch } = await import("node-fetch");
const url = `https://newsapi.org/v2/top-headlines?category=${category}&apiKey=${apiKey}`;
const response = await fetch(url);
const data = await response.json();
res.json(data);
} catch (error) {
console.error("Error fetching news:", error.message);
res.status(500).json({ error: "Error fetching news" });
}
});
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`);
});
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>News App</title>
</head>
<body>
<h1>News App</h1>
<select id="category">
<option value="general">General</option>
<option value="business">Business</option>
<option value="sports">Sports</option>
<option value="technology">Technology</option>
</select>
<button onclick="getNews()">Get News</button>
<div id="news"></div>
<script>
async function getNews() {
const apiKey = "cc6cda365d534d32afd2d4bfbdd671fa";
const category = document.getElementById("category").value;
const url = `http://localhost:3000/news?category=${category}`;
try {
const response = await fetch(url);
const data = await response.json();
if (data.articles) {
displayNews(data.articles);
} else {
throw new Error(data.message || "Не удалось получить новости");
}
} catch (error) {
console.error("Error when receiving news:", error.message);
}
}
function displayNews(articles) {
const newsContainer = document.getElementById("news");
newsContainer.innerHTML = "";
articles.forEach((article) => {
const articleElement = document.createElement("div");
articleElement.innerHTML = `
<h2>${article.title}</h2>
<p>${article.description}</p>
<a href="${article.url}" target="_blank">Read more</a>
`;
newsContainer.appendChild(articleElement);
});
}
</script>
</body>
</html>
我尝试查看文档,但没有找到任何内容,我在 Apollo 客户端也有类似的问题(ApolloError:网络错误),它在同一个项目中使用了 Nest.js-server
问题是 url 使用的是 localhost。首先你需要了解你的 IP 地址,然后用该地址替换 localhost
const IP_ADDRESS = '10.0.0.2'
const url = 'http://${IP_ADDRESS}:3000/news?category=business'