You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何运行React+Express+Axios项目及接口数据获取问题求助

Solutions to Your React + Express + Axios Questions

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 concurrently
    
  • Install 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 concurrently as a dev dependency in the root myapp/ directory to run both servers at once:
      npm install concurrently --save-dev
      
  • 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.json scripts to run both servers:
    Modify your existing root package.json to 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 root myapp/ directory, run:

    npm start
    

    This 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 concurrently is in your devDependencies by running npm list concurrently. If not, reinstall it with npm 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 the server script to node server.js.
  • Port conflicts: Ensure no other processes are using port 9000 or 3000. On macOS/Linux, use lsof -i :9000 to check; on Windows, use netstat -ano | findstr :9000. Kill conflicting processes if needed.
  • Quotation marks: On Windows, use double quotes around each script in the concurrently command; 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:18:51