【发布时间】:2019-07-28 10:32:57
【问题描述】:
我正在尝试使用 NodeJS、Express 和 MongoDB 执行 PUT 请求。我目前遇到的问题是我不断收到error **400**,但我不确定具体原因。
我真正想做的是在某个用户注册后上传编辑我的USER集合中的field。这应该发生在特定的/user/edit/:id 路由上。
我的应用程序采用标准 MVC 模式构建。
这是我的Mongo Schema 的结构:
let UserSchema = new mongoose.Schema({
username: String,
password: String,
email: String,
avatar: String,
firstName: String,
lastName: String,
laps:[{ type: Schema.Types.ObjectId, ref: 'Stats' }]
});
这是我的服务:
exports.updateUser = async function(user) {
let id = user.id;
let oldUser;
try {
//Find the old User Object by the Id
oldUser = await User.findById(id);
} catch(e) {
throw Error("Error occured while Finding the User");
}
// If no old User Object exists return false
if (!oldUser) {
return false;
}
//Edit the User Object
oldUser.firstName = user.firstName || oldUser.firstName;
oldUser.lastName = user.lastName || oldUser.lastName;
oldUser.avatar = user.avatar || oldUser.avatar;
try {
let savedUser = await oldUser.save();
return savedUser;
} catch(e) {
throw Error("And Error occured while updating the User");
}
};
我正在使用的控制器:
exports.updateUser = async function(req, res, next) {
if (!req.body._id){
return res.status(400).json({status: 400, message: "Id must be present"})
}
let id = req.body._id;
let user = {
id,
firstName: req.body.firstName || null,
lastName: req.body.lastName || null,
avatar: req.body.avatar || null
};
try {
let updatedUser = await UserService.updateUser(user);
return res.status(200).json({status: 200, data: updatedUser, message: "Successfully Updated User"})
} catch(e) {
return res.status(400).json({status: 400, message: e.message})
}
};
路由文件中的路由路径:
router.post('/edit/:id', UserController.updateUser);
服务器文件中用户的路由路径:
app.use('/user', require('./api/routes/user.route'));
我知道大多数4** 错误来自应用程序的前端,所以我还将发布我的表单和它背后的构造函数。我使用 ReactJS 作为框架。
前端表单:
class UserProfile extends Component {
constructor(props) {
super(props);
this.state = {
avatar: '',
resultsSubmitted: false
};
this.formChange = this.formChange.bind(this);
this.resultsSubmit = this.resultsSubmit.bind(this);
}
formChange(e) {
console.log("form changed" + e.target);
const { name, value } = e.target;
this.setState({ [name]: value });
}
resultsSubmit(e) {
e.preventDefault();
const accessToken = JSON.parse(localStorage.getItem('auth_user')).data.access_token;
const { avatar } = this.state;
const { dispatch } = this.props;
if (avatar) {
console.log("submitting results: " + avatar);
dispatch(userActions.addAvatar(avatar, accessToken));
}
}
render(){
const { avatar, resultsSubmitted} = this.state;
return (
<div className="container-fluid no-gutters page-login">
<div className="row">
<div className="login-wrapper">
<h2> Edit User Profile </h2>
<form onSubmit={this.resultsSubmit}>
<div className="form-group">
Paste Avatar URL: <input type="text" value={avatar} name="avatar" id="" onChange={this.formChange} />
</div>
<input type="submit" className="btn btn-primary btn-lg btn-block" value="submit"/>
</form>
</div>
</div>
</div>
)
}
}
function mapStateToProps(state) {
const { layout } = state;
return {
layout
};
}
export default connect(mapStateToProps)(UserProfile);
我的派遣:
function addAvatar(avatar, token) {
return dispatch => {
dispatch(request());
userService.addAvatar(avatar, token)
.then(
user => {
dispatch(success(user));
history.push(`${process.env.PUBLIC_URL}/`);
},
error => {
dispatch(failure(error));
dispatch(alertActions.error(error));
}
);
};
function request() { return { type: userConstants.AVATAR_REQUEST } }
function success(user) { return { type: userConstants.AVATAR_SUCCESS, user } }
function failure(error) { return { type: userConstants.AVATAR_FAILURE, error } }
}
HTTP Post 服务:
function addAvatar(avatar){
const requestOptions = {
method: 'POST',
headers: authHeader(),
body: avatar
};
return fetch('http://localhost:3003/user/edit/:id', requestOptions)
.then(response => {
if (!response.ok) {
console.log("+",response,"+");
return Promise.reject(response.statusText);
}else{
console.log(response, "the user service response was gooooooooooood");
}
return response.json();
})
.then(data => console.log(data,"WHT DO WE HAVE HERE?"));
}
为巨大的代码墙道歉,但我想包括所有位。
我在路由 POST 上收到错误 400(错误请求)
http://localhost:3003/user/edit/:id
【问题讨论】:
-
您在开发者工具的网络选项卡中遇到什么错误?这可能是 CORS 问题。
-
我认为这可能是因为
id字段在您正在创建的用户 JSON 对象中没有键。您可以尝试将其更改为id: id看看是否有帮助?