【问题标题】:undefined values on post method from react app来自反应应用程序的 post 方法的未定义值
【发布时间】:2020-08-25 06:51:19
【问题描述】:

当我将这些值发送到 api 时,我得到了未定义的值。 注意:我使用邮递员,效果很好。 这是我在 react 应用上的代码

 submithandler=(e)=>{
      e.preventDefault();
     axios.post('http://localhost:8000/api/addsickers',
     JSON.stringify({
         ID:"123456789",
         Blod:"22334445",
         Allergic:"6677788",
         Chronic:"3445566"
        })
     )
       .then(response=>{
           alert(response);
       })
       .catch(err=>{
           alert("catch"+err);
       });
  }

这是 api 代码:

 var person = req.body;
    /* const schema = joi.object().keys({
         ID: joi.string().min(5).max(50).required(),
         Blod: joi.string().required(),
         Allergic: joi.string(),
         Chronic: joi.string(),
     });*/
    // validate data
    // if (!joi.validate(person, schema)) {
    con.connect();
    con.query('INSERT INTO `sick`(`ID`, `Blod`, `Allergic`, `Chronic`) VALUES ("' + person.ID + '","' + person.Blod + '","' + person.Allergic + '","' + person.Chronic + '")', function(err, rows, fields) {

            if (err) {
                // res.send(toString(err));
                console.log(err);
            }
            // res.send("registred succefully");
        })
        // } else {
        //   res.send("please validate your data");
        //}
        //ID + Blod + allergic + chronic +
    con.end()
    console.log(req.body);

注意:console.log(person) 向我显示了一个 json 数组,表示数据已传输。 但在插入时已定义,例如“person.ID”未定义。 问题是如何从这个 json 数组中获取未定义的值。 因为我尝试了一些方法,但对我不起作用。 提前致谢。

【问题讨论】:

  • 请提供服务器和客户端代码,也许这可以帮助stackoverflow.com/questions/16134378/…
  • 感谢您的回复,我已经编辑了错误,我提到的第一个错误与get方法有关,应用程序崩溃我已经解决了,但与post方法有关的错误是这个错误我已经添加了,请再看一遍。
  • 也许你没有使用 body-parser。但是我们只能确认您是否将完整的代码从您声明模块 express 的服务器中放入。我们可以确认您是否发送typeof req.body
  • 我在客户端的 post 方法中发现了问题,主体数据的类型在发布到 api 时返回一个长字符串,当我使用 postman 它返回一个 json 数组时,我有在这里问了完整的问题stackoverflow.com/questions/61705905/json-post-method-format/…
  • 不建议为一个问题创建多个问题,当需要更新问题时,如果要单独更新,只需使用标题###UPDATE 1/2/3///

标签: mysql node.js reactjs express


【解决方案1】:

它是通过以下方式之一修复的,但我更喜欢第一种方式:

首先你可以将 cors 添加到 api

npm install cors 

const cors =require('cors')

app.use(cors())

router.post('path',cors(),(req,res).....

第二个是添加:

JSON.parse(req.body)

以 json 格式读取数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-09
    • 2011-03-13
    • 1970-01-01
    相关资源
    最近更新 更多