【问题标题】:POST method not working ReactJs, NodeJs, ExpressJsPOST 方法不起作用 ReactJs、NodeJs、ExpressJs
【发布时间】:2022-07-20 22:13:39
【问题描述】:

错误->
POST method error

上面的 post 方法不工作,但类似的 get 方法版本工作

我有以下代码:
App.js

  • 与后端通信
handleData = async (url) => {
    const newData = await fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
        },
        body: JSON.stringify({
            id_: this.state.id,
            firstName: this.state.firstName,
            lastName: this.state.lastName,
            email: this.state.email,
            password: this.state.password,
        }),
    }).then(res => res.json());

    console.log('newData-', newData);
    return newData;
}
  • 表格
<form action='/mainApp' method='GET' onSubmit={this.handleSubmit} id="signUpForm">

sever.js

app.post('/mainApp/show', async (req, res) => {
    console.log('Show called');
    const result = await dbOperation.showVals(req.body.name);
    res.send(result.rows);
});

app.post('/mainApp/insert', async (req, res) => {
    console.log('Insert called');
    const result = await dbOperation.showVals('email', req.body.email);
    console.log(result.rows.length);
    if (result.rows.length > 0) {
        console.warn('Duplicate email address');
        res.send({ errorPresent: true, errorMessage: 'Duplicate email address' });
    } else {
        console.log('Inserting', req.body.id_, req.body.firstName, req.body.lastName, req.body.email, req.body.password);
        await dbOperation.insertVals(req.body.id_, req.body.firstName, req.body.lastName, req.body.email, req.body.password);
        res.send({ errorPresent: false, errorMessage: 'No error' });
    }
});

我尝试将所有内容都转换为 GET 并且可以正常工作

【问题讨论】:

    标签: node.js reactjs forms express post


    【解决方案1】:

    它适用于 get 方法,因为您正在发送一个 GET 请求

    <form action='/mainApp' method='GET' onSubmit={this.handleSubmit} id="signUpForm">
    

    对于 POST req,您必须将表单内的方法更改为

    <form action='/mainApp' method='POST' onSubmit={this.handleSubmit} id="signUpForm">
    

    【讨论】:

      猜你喜欢
      • 2012-09-12
      • 2019-05-23
      • 2016-12-20
      • 2017-06-02
      • 2023-04-04
      • 2018-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多