首頁  >  問答  >  主體

使用 onSubmit 從 React 向 Node js 發送數據

我的 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));
}

它應該將資料發送到我的節點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)未定義。如果有人可以幫助我,我將不勝感激。謝謝

P粉281089485P粉281089485224 天前334

全部回覆(1)我來回復

  • P粉308783585

    P粉3087835852024-04-03 09:16:55

    我編輯瞭如下程式碼,現在我可以從我的 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 行是問題所在。

    回覆
    0
  • 取消回覆