如何运行React+Express+Axios项目及接口数据获取问题求助
Hey there! Let's tackle your two technical issues step by step—no jargon, just actionable steps to get your project working right.
1. How to Run a React + Express + Axios Project
Running a project combining these three tools is all about setting up a clear structure and coordinating the frontend and backend servers. Here's a straightforward workflow:
Set up your project structure (recommended for separation of concerns):
myapp/ ├── client/ # React frontend │ └── (create-react-app files) ├── server/ # Express backend │ └── server.js └── package.json # Root config for concurrentlyInstall dependencies:
- For the Express server (in
server/directory):npm init -y npm install express - For the React client (in
client/directory, using Create React App):npx create-react-app client cd client npm install axios - Install
concurrentlyas a dev dependency in the rootmyapp/directory to run both servers at once:npm install concurrently --save-dev
- For the Express server (in
Configure your Express server (
server/server.js):
Add a simple endpoint to return your people data, like this:const express = require('express'); const app = express(); const PORT = 9000; // Sample people data const people = [ { id: 1, name: "Alice" }, { id: 2, name: "Bob" }, { id: 3, name: "Charlie" } ]; app.get('/people', (req, res) => { res.json(people); }); app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); });Update root
package.jsonscripts to run both servers:
Modify your existing rootpackage.jsonto include these scripts:{ "name": "myapp", "version": "0.1.0", "private": true, "dependencies": { "axios": "^0.18.0", "express": "^4.16.3", "react": "^16.3.1", "react-dom": "^16.3.1", "react-scripts": "your-version-here" }, "devDependencies": { "concurrently": "^7.6.0" // Use the latest compatible version }, "scripts": { "start": "concurrently \"npm run server\" \"npm run client\"", "server": "node server/server.js", "client": "cd client && npm start" } }Run the project:
In the rootmyapp/directory, run:npm startThis will spin up both the Express server on port 9000 and the React dev server (usually port 3000).
2. Fixing Concurrently Failures & Fetching Data to React State
Fixing Concurrently Issues
If concurrently is failing, here are the most common fixes:
- Check installation: Verify
concurrentlyis in yourdevDependenciesby runningnpm list concurrently. If not, reinstall it withnpm install concurrently --save-dev. - Verify script paths: Double-check that paths in your scripts match your project structure. For example, if your Express server is in the root folder instead of
server/, update theserverscript tonode server.js. - Port conflicts: Ensure no other processes are using port 9000 or 3000. On macOS/Linux, use
lsof -i :9000to check; on Windows, usenetstat -ano | findstr :9000. Kill conflicting processes if needed. - Quotation marks: On Windows, use double quotes around each script in the
concurrentlycommand; on macOS/Linux, you can use single quotes or escape double quotes.
Fetching Data to React State
To get the http://localhost:9000/people data into your React component's this.state.persons, use Axios in the componentDidMount lifecycle method (since you're using class components with React 16.3). Here's a complete component example:
import React, { Component } from 'react'; import axios from 'axios'; class PeopleList extends Component { constructor(props) { super(props); this.state = { persons: [] // Initialize empty array }; } componentDidMount() { // Fetch data when component mounts axios.get('http://localhost:9000/people') .then(response => { // Update state with fetched names this.setState({ persons: response.data }); }) .catch(error => { console.error('Error fetching data:', error); }); } render() { return ( <div> <h2>People List</h2> <ul> {this.state.persons.map(person => ( <li key={person.id}>{person.name}</li> ))} </ul> </div> ); } } export default PeopleList;
Important fix for CORS errors: Since React runs on port 3000 and Express on 9000, you'll likely hit cross-origin issues. Fix this by installing the cors package in your Express server:
cd server npm install cors
Then add it to your server.js:
const cors = require('cors'); app.use(cors()); // Add this before your routes
内容的提问来源于stack exchange,提问作者Jota

