【问题标题】:How to send data from react and use the request body in express, using Axios?如何使用 Axios 从反应中发送数据并使用快递中的请求正文?
【发布时间】:2021-06-17 16:12:23
【问题描述】:

我在 react 中使用状态来保存一些表单数据,我想要的是,当我在 react 中提交表单时,我使用 axios 发送一个 post 请求,并且我想在 express 中使用表单数据。我尝试req.body.paramsreq.body.data req.body general 来访问请求有效负载,它们都返回未定义。基本上我想快速访问general(form data)。我该怎么做?

注意:状态被命名为general,oneSuggestion,它们是基本的字符串状态。

注意:我搜索了几个小时的类似问题,但没有一个能解决我的问题。如果有解决办法,我没找到,请见谅。

编辑:评论数据,并将状态直接放在帖子中。

反应代码:

      function handleSubmit(e) {
        e.preventDefault();
        console.log(general, suggestionsForCases);
        /*
                        let data = {
                        general: general,
                        oneSuggestion: oneSuggestion,
                        };
                        data = JSON.stringify(data);
                        console.log(data);
                        */

        let axiosConfig = {
        headers: {
            "Content-Type": "application/json;",
            "Access-Control-Allow-Origin": "*",
        },
        };
        axios
        .post(
            "http://localhost:8000/dict/",
            { general: general, oneSuggestion: oneSuggestion },
            axiosConfig
        )
        .then((res) => console.log("success, dictionary sent,", res))
        .catch((err) => {
            console.log(err.response);
        });
    }
    function handleInput(e) {
        if (e.target.name == "general") {
        setGeneral(e.target.value);
        console.log(general);
        }
        if (e.target.name == "oneSuggestion") {
        setOneSuggestion(e.target.value);
        console.log(oneSuggestion);
        }
    }

    return (
        <div>
        <form onSubmit={handleSubmit}>
            <label>
            general:
            <textarea name="general" onChange={handleInput}></textarea>
            </label>

            <label>
            suggestion:
            <input name="oneSuggestion" onChange={handleInput}></input>
            </label>
            <button type="submit">submit</button>
        </form>
        </div>
    );
    }
    export default AddDictionary;



        

快递代码:

    const express = require("express");
    const router = express.Router();

    const Dictionary = require("../database/category/dictionary");

    router.use(express.json());

    router.get("/", (req, res) => {
    console.log("success");
    res.json({ msg: "success"});
    });
    router.post("/", (req, res) => {
    console.log(req.body.general);
    res.json({
        msg: "success",
    });
    });

    module.exports = router;

【问题讨论】:

  • 看起来你发送的是{params:{general:""}}而不是{general:""}
  • 我认为在发送数据之前也没有必要对数据进行字符串化,因为 axios 会为你这样做
  • 嘿,我试过了,但仍然返回未定义:axios .post( "http://localhost:8000/dict/", { general: general, oneSuggestion: oneSuggestion },axiosConfig)

标签: node.js reactjs express axios


【解决方案1】:

好的,我发现了问题。我根据 source 从帖子中删除了 axiosConfig,现在这是工作代码:

         axios
        .post(
            "http://localhost:8000/dict/",
            { general: general, oneSuggestion: oneSuggestion }
        )
        .then((res) => console.log("success, dictionary sent,", res))
        .catch((err) => {
            console.log(err.response);
        });

谢谢你们的帮助。

【讨论】:

    【解决方案2】:

    您需要中间件来解析请求并使其在req.body 中可访问。我假设您使用的是 4.16 之后的版本,该版本引入了 express.json() 作为此场景的中间件。如果您使用的是早期版本,我会更新我的答案。

    使用您的代码作为启动器的示例:

    const express = require('express');
    const app = express();
    
    app.use(express.json());
    
    app.post('/', (req, resp) => {
      console.log(request.body.params);
    });
    
    app.listen(3000);
    

    解释一下,您发布的任何内容,也就是假设您发布了以下对象:

    {
      fruit: 'apple',
      vegetable: 'onion'
    }
    

    使用解析器后,您将访问req.body.fruitreq.body.vegetable 中发布的数据。

    【讨论】:

    • 嘿,我已经按照你说的做了,并且编辑了上面的 express 代码,但是当我使用 req.body.general 时,仍然返回 undefined。
    猜你喜欢
    • 2019-03-04
    • 2020-08-16
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 2022-12-16
    • 2017-11-02
    • 2022-01-21
    • 1970-01-01
    相关资源
    最近更新 更多