【问题标题】:When I post data with fetch post, I don't receive data当我使用 fetch post 发布数据时,我没有收到数据
【发布时间】:2022-01-23 18:51:00
【问题描述】:

我在获取帖子时遇到问题,我想将数据发送到一个 url 但它不起作用..

function TodoTaskForm () {
    const taskContentInput = useRef(null)
    const handleSubmit = async (e) => {
        e.preventDefault()
        fetch('/api/tasks', {
            method: 'POST',
            body: JSON.stringify({content: taskContentInput.current.value})
        })
    }

    return (
        <form onSubmit={handleSubmit} className="__component_todolist_form_container">
            <input type="text" name="task" ref={taskContentInput} placeholder="nouvelle tâche.."></input>
        </form>
    )
}

在我的组件中,我正在执行此操作,并且在我的快速服务器中:

app.post('/api/tasks', (req, res) => {
    console.log(req.body)
    console.log('request received!')
})

当我测试时,我收到了请求,但 req.body 在我的控制台中返回“{}”,我不明白,我正在使用 app.use(express.json()) 但它不起作用,我甚至尝试使用 body-parser 但是... 所以拜托,我需要帮助..谢谢!

【问题讨论】:

    标签: javascript node.js reactjs express fetch


    【解决方案1】:

    你需要:

    1. 与正在发送的数据匹配的正文解析器。您已从发送表单编码数据切换到发送 JSON。注意Express has built-in body parsing middleware 不需要单独的body-parse NPM 模块。
    2. 请求中的 Content-Type 标头说明数据的格式,以便可以触发正确的正文解析器。

    这样的:

    app.post('/api/tasks', express.json(), (req, res) => {
        console.log(req.body)
        console.log('request received!')
    })
    

    fetch('/api/tasks', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({content: taskContentInput.current.value})
    })
    

    【讨论】:

    • 谢谢,它正在工作!我忘记了标题
    猜你喜欢
    • 1970-01-01
    • 2020-01-27
    • 1970-01-01
    • 2012-04-03
    • 2019-09-11
    • 2015-05-15
    • 1970-01-01
    • 2020-11-16
    • 2018-11-24
    相关资源
    最近更新 更多