首页 > 解决方案 > Req.body 返回错误类型的对象

问题描述

我正在向后端发送一个简单的注册表单(POST fetch)进行处理。但是,请求正文没有按应有的方式收到。

我希望看到 request.body = {"username": "john", "password": "password"}

但是当我在控制台记录它时,我看到 { '{"username":"car","password":"car"}': '' }

这是我的收获:

fetchRegister = (e) => { //triggered when submitting Register Info
      e.preventDefault();
      const registerOptions = {
        method: "POST",
        mode: "no-cors",
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
        body: JSON.stringify({
          username: this.state.regUsername, //The inputChange function will set these to whatevr the user types
          password: this.state.regPassword,
        }),
    }
      fetch("http://localhost:5000/register", registerOptions)
      .then(response => response.json())
      .then(data => 
        console.log(data)
      )
    }

这是我的终点:

app.use(bodyParser.urlencoded({ extended: true}))
app.use(bodyParser.json());

app.post('/register', (req, res) => {
    console.log(req.body);
    const inputUsername = req.body.username;
    const inputPassword = req.body.password;

    let newUser = new User({
        userName: inputUsername, 
        password: inputPassword
    })

    bcrypt.genSalt(10, (err, salt) => {
        bcrypt.hash(newUser.password, salt, function(err, hash) {
            if(err) {
                res.send(err);
            }
            newUser.password = hash;

            newUser.save((err) => {
                if (err) {
                    console.log(err)
                    res.send(JSON.stringify({'message': 'Username is already taken'}));
                }else {
                    res.send(JSON.stringify({'message': 'you were successful'}));
                }
            })
        });
    })
})



<div id="registerForm"> 
    <form>
    <legend>Register:</legend>
    Choose a Username:<input className="reg" value={this.state.regUsername} onChange={this.inputChange("regUsername")} required></input>
   Choose your Password:<input className="reg" type="password" value={this.state.regPassword} onChange={this.inputChange("regPassword")} required></input>
    <button className="FORMbtn" onClick={this.fetchRegister} type="submit">Register Me</button>
              </form>
            </div>

我只想将一个标准对象发送到我的后端。我不知道是 CORS 还是我的应用程序类型搞砸了。它在邮递员中工作得很好。

标签: javascriptreactjsexpressfetch

解决方案


这是一个 CORS 问题。我必须使用 NPM 安装“cors”,并将其带入 Express。然后我可以拿出来'mode': 'no-cors',它奏效了。


推荐阅读