我尝试在 React 组件中使用 Axios 请求从服务器获取书籍列表。
const express = require('express');
const app = express();
const books = [
{ id: 1, title: 'Harry Potter and the Sorcerer\'s Stone', author: 'J.K. Rowling' },
{ id: 2, title: 'The Hobbit', author: 'J.R.R. Tolkien' },
{ id: 3, title: 'To Kill a Mockingbird', author: 'Harper Lee' }
];
app.get('/api/books', (req, res) => {
res.json(books);
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const BookList = () => {
const [books, setBooks] = useState([]);
useEffect(() => {
axios.get('http://localhost:3000/api/books')
.then(response => {
setBooks(response.data);
})
.catch(error => {
console.error('Error fetching books:', error);
});
}, []);
return (
<div>
<h2>Book List</h2>
<ul>
{books.map(book => (
<li key={book.id}>{book.title} by {book.author}</li>
))}
</ul>
</div>
);
};
export default BookList;
尽管服务器正在运行并且可以在指定端点访问,但您还是遇到了网络错误并且无法检索图书列表。
CORS(跨源资源共享)问题。它是 Web 浏览器实现的一项安全功能,用于限制网页向与原始网页提供服务的域不同的域发出请求。该错误特别指出请求的资源上不存在“Access-Control-Allow-Origin”标头。
要解决此问题,只需在 Express 服务器中安装 cors 并更新代码,如下所示,它应该可以正常工作:
npm i cors
.
const express = require('express');
const app = express();
const cors = require('cors')
const books = [
{ id: 1, title: 'Harry Potter and the Sorcerer\'s Stone', author: 'J.K. Rowling' },
{ id: 2, title: 'The Hobbit', author: 'J.R.R. Tolkien' },
{ id: 3, title: 'To Kill a Mockingbird', author: 'Harper Lee' }
];
app.use(cors());
app.get('/api/books', (req, res) => {
res.json(books).status(200);
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});