我正在向后端发送一个简单的注册表(POST提取)以进行处理。但是,请求主体没有收到应有的状态。
我希望看到request.body = {“用户名”:“ john”,“密码”:“密码”}
但是我在控制台登录时看到 {'{“用户名”:“汽车”,“密码”:“汽车”}':''}
这是我的收藏夹
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还是我的应用程序类型搞砸了。在邮递员中效果很好。
答案 0 :(得分:0)
这是一个CORS问题。我必须在NPM上安装“ cors”,然后将其带入Express。然后我可以取出'mode': 'no-cors'
,它起作用了。