javascript - 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 还是我的应用程序类型搞砸了。它在邮递员中工作得很好。
解决方案
这是一个 CORS 问题。我必须使用 NPM 安装“cors”,并将其带入 Express。然后我可以拿出来'mode': 'no-cors'
,它奏效了。
推荐阅读
- angularjs - 有没有办法在angularJS中翻译成另一种语言的月份和日期名称?
- mysql - 这个使用 order by 和 left join 的 sql 查询有什么问题?这是正确的方法吗?
- c# - 如何使用信号器以正确的方式处理更新?
- c# - C# Windsor.Castle 异常无法实例化 ApplicatioName.MainWindow
- redis - 从服务器读取行时出现 Predis 错误,超时修复
- r - 如何添加具有顺序值的列以扩展 R 中的数据框
- arrays - 如何修复这个 Eslint 使用扩展运算符而不是 '.apply()'
- node.js - 从地图循环中获取数据
- r - 如何使用 R 转换为日期格式以及缺少周末日期是否会成为 Arima / Prophet 预测模型的问题?
- reactjs - 谷歌一键登录弹出窗口未显示