【问题标题】:Req.body is returning the wrong kind of objectReq.body 返回错误类型的对象
【发布时间】:2018-06-27 21:56:15
【问题描述】:

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

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

但是当我在控制台记录它时,我看到了 { '{"用户名":"汽车","密码":"汽车"}': '' }

这是我的获取:

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 还是我的应用程序类型搞砸了。它在邮递员中工作得很好。

【问题讨论】:

  • 您忘记为 json 添加 bodyparser。或者,无论出于何种原因,它都没有按此请求运行。 ("Content-Type": "application/x-www-form-urlencoded", 是个好理由)
  • 您的内容类型与您发送的内容不匹配。
  • 您能详细说明一下 Content-Type 问题吗?如果不是那种内容类型,它甚至不会发送
  • 哦,它会发送它就好了。但是,服务器不会正确解释它。
  • 接下来我应该尝试哪种内容类型?我尝试了不起作用的“应用程序/json”

标签: javascript reactjs express fetch


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-15
    • 2018-03-10
    • 2022-01-23
    • 2013-10-30
    • 1970-01-01
    相关资源
    最近更新 更多