React POST form Fetch but Undefined data

问题描述 投票:0回答:1

[所有人,这是我的第一个问题,对这个不好的问题感到抱歉,但是我是REACT的新手。我正在独自尝试,但无法正常工作

这是我从中获取的帖子

const connect = () =>{
var data = {
  'email':email,
  'password':password
}
console.log(data)
    fetch('http://localhost:8088/sign-up', {
        method: 'POST',
        mode:"no-cors",
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
        .then((res) => { res.json() })
        .then((data) => {
            console.log("Completed")
        })
        .catch((err) => {
            console.log(err);
        })

}

这是我的服务器,我不知道为什么它不能从react读取数据

app.post('/sign-up', (req, res) => {
let name = req.body.name;
let personal_id = req.body.personal_id;//Using Personal ID for username
let email = req.body.email;
let password = req.body.password;
let birthday = req.body.birthday;
let sex = req.body.sex;
let telephone = req.body.telephone;
let job = req.body.job;
let addressing = req.body.addressing;
let num_live = req.body.num_live;
let saltRounds = 10;//Hashing setup
console.log(req.body)
//Hashing process
bcrypt.hash(password, saltRounds, (err, password) => {
    if (err) {
        return console.log(err.message);
    }

    let obj = {
        personal_id, password, name, email, birthday, sex, telephone, job, addressing, num_live,
        address: { $ref: 'address', $id: req.session.address_id }
    }
    db.collection('users').insertOne(obj, (err, result) => {
        if (err) {
            return res.send(err);
        }
        return res.send('Sign up complete');
    });
});

});

结果[发布的结果] [3]

会发生什么?当我将数据发布到服务器时,为什么服务器找不到数据。它显示了未定义的位置

node.js reactjs post fetch
1个回答
0
投票

connect函数中,没有为emailpassword接受任何参数。这就是为什么它没有定义的原因。您可以将emailpassword作为参数传递,也可以只是调试而已,就可以在变量本身中对其进行硬编码,以测试API响应。

const data = {
  email:"[email protected]",
  password:"123"
}

如果将emailpassword用作函数参数,则可以这样做。

const connect = (email,password) =>{
const data = {
  email:email,
  password:password
}
/* rest of the code */
}
© www.soinside.com 2019 - 2024. All rights reserved.