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

React应用提交数据后Express控制台无输出,求排查解决

React与Express连接问题:POST请求无控制台输出排查

我正在学习将Express路由与React应用连接,React端通过axios发送POST请求到Express的/post_name路由,但Express控制台始终没有打印提交的name值。React和Express服务都能正常启动,已安装必要依赖(nodemon、express、axios、cors),跨域也配置了。


问题代码

React端 App.js

import axios from "axios"
import React, { useState } from "react"
import "./App.css"

function App() {
    const [ name, setName ] = useState("")
    const [ home, setHome ] = useState("")

    useEffect(() => {
        axios.get("http://localhost:4000/home").then(function(response) {
            setHome(response.data)
        })
    }, [])

    async function postName(e) {
        e.preventDefault()
        try {
            await axios.post("http://localhost:4000/post_name", {
                name
            })
        } catch (error) {
            console.error(error)
        }
    }

    return (
        <div className="App">
            <form onSubmit={postName}>
                <input type="text" value={name} onChange={(e) => setName(e.target.value)} />
                <button type="submit">Send Name</button>
            </form>
            {home}
        </div>
    )
}

export default App

Express端 index.js

const express = require("express")
const app = express()
const port = 4000
const cors = require("cors")

// npm init
// npm i express cors nodemon
// they add a handy req.body object to our req,
// containing a Javascript
//  object representing the payload sent with the request

app.use(express.urlencoded({ extended: true }))
app.use(express.json())
app.use(cors())

app.get("/", cors(), async (req, res) => {
    res.send("This is working")
})
app.get("/home", cors(), async (req, res) => {
    res.send("This is the data for the home page")
})

app.post("/post_name", async (req, res) => {
    let { name } = req.body
    console.log(name)
})
app.listen(port, () => {
    console.log(`Listening at http://localhost:${port}`)
})

问题原因与修复步骤

1. React端缺少useEffect导入(核心问题)

代码中使用了useEffect但未在React的导入语句中声明,会导致组件运行时报错,直接影响表单提交逻辑的执行。

修复:
在import语句中添加useEffect:

import React, { useState, useEffect } from "react"

2. Express路由未返回响应

/post_name路由处理函数没有向客户端返回任何响应,会导致axios的POST请求一直处于挂起状态,不仅可能隐藏日志输出,还会引发请求超时问题。

修复:
在路由处理末尾添加响应,告知客户端请求已处理完成:

app.post("/post_name", async (req, res) => {
    let { name } = req.body
    console.log(name)
    // 返回JSON格式响应
    res.status(200).json({ message: "名称已接收", receivedName: name })
    // 或返回文本响应
    // res.send("Name received successfully")
})

3. 可选:添加请求验证日志

可以在Express路由中添加前置日志,确认请求是否真的到达服务器:

app.post("/post_name", async (req, res) => {
    console.log("POST请求已到达服务器")
    let { name } = req.body
    console.log("提交的名称:", name)
    res.status(200).json({ message: "名称已接收", receivedName: name })
})

修复后完整代码

修复后的App.js

import axios from "axios"
import React, { useState, useEffect } from "react"
import "./App.css"

function App() {
    const [ name, setName ] = useState("")
    const [ home, setHome ] = useState("")

    useEffect(() => {
        axios.get("http://localhost:4000/home").then(function(response) {
            setHome(response.data)
        })
    }, [])

    async function postName(e) {
        e.preventDefault()
        try {
            const response = await axios.post("http://localhost:4000/post_name", {
                name
            })
            console.log("服务器响应:", response.data)
        } catch (error) {
            console.error(error)
        }
    }

    return (
        <div className="App">
            <form onSubmit={postName}>
                <input type="text" value={name} onChange={(e) => setName(e.target.value)} />
                <button type="submit">Send Name</button>
            </form>
            {home}
        </div>
    )
}

export default App

修复后的index.js

const express = require("express")
const app = express()
const port = 4000
const cors = require("cors")

app.use(express.urlencoded({ extended: true }))
app.use(express.json())
app.use(cors())

app.get("/", cors(), async (req, res) => {
    res.send("This is working")
})
app.get("/home", cors(), async (req, res) => {
    res.send("This is the data for the home page")
})

app.post("/post_name", async (req, res) => {
    console.log("POST请求已接收")
    let { name } = req.body
    console.log("提交的name:", name)
    res.status(200).json({ message: "Name received", name: name })
})

app.listen(port, () => {
    console.log(`Listening at http://localhost:${port}`)
})

内容的提问来源于stack exchange,提问作者chuck roth

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 14:55:23