使用onSubmit从react发送数据到Node js

fhity93d  于 2023-04-11  发布在  Node.js
关注(0)|答案(1)|浏览(83)

我在我的React脚本中有这个onSubmit,当我点击提交按钮时会调用它:

const handleSubmit = (event) => {
event.preventDefault();
const form = event.target;
const rawdata = new FormData(form);
const data = {
    email: rawdata.get('email'),
    password: rawdata.get('password'),
};

console.log(data);
const response = fetch('http://localhost:4000/register', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify(data),
}).then(response => {
    if(response.ok) {
        console.log('Form data sent successfully');
    } else {
        console.error('Failed to send form data');
    }
}).catch (error => console.error(error));
}

它应该向我的node js脚本发送数据并调用以下函数:

app.post("/register", function (req, res){
    console.log("inside /register");
    console.log("email: " + req.body.email);
    User.register({username: req.body.email}, req.body.password, function(err, user){
        if(err) {
            console.log(err);
            console.log("couldn't register");
            //res.redirect("/signup");
        } else{
            passport.authenticate("local")(req, res, function(){
                console.log("login granted");
            });
        }
    });
});

但它说,我试图记录的数据(req.body.email)是未定义的。如果有人能帮助我与此。谢谢

toe95027

toe950271#

我按如下方式编辑了代码,现在我可以从node js脚本中的react脚本获取数据:

const handleSubmit = (event) => {
    event.preventDefault();
    const form = event.target;
    const rawdata = new FormData(form);
    const data = {
        email: rawdata.get('email'),
        password: rawdata.get('password'),
    };

    console.log(data);
    fetch('http://localhost:4000/register', {
        method: 'POST',
        headers:{
            'Content-Type' : 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(response => {
        console.log("response ok: " + response.ok);
        console.log("response status: " + response.status);
        console.log("response json: " + response.json());
        if(response.ok) {
            console.log('Form data sent successfully');
            return response.json();
        } else {
            console.error('Failed to send form data');
        }
    }).catch (error => console.error(error));

在我的节点脚本中,我必须在开头添加以下行:

app.use(bodyParser.json());
app.use(express.static("public"));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({
   extended: true
}));

现在它工作了。节点中的app.use行是问题所在。

相关问题