mongoose
架构carNumber
应该是唯一的:
var Schema = mongoose.Schema({
createdAt: {
type: Date,
default: Date.now
},
carNumber: {
type: String, index: {unique: true, dropDups: true},
},
carOwner: String
});
使用express
控制器功能数据保存到db:
export const addCar = (req, res) => {
const newCar = new Car(req.body);
newCar.save((err, car) => {
if (err) {
return res.json({ 'success': false, 'message': 'Some Error' });
}
return res.json({ 'success': true, 'message': 'Car '+ car.carNumber +' added successfully', car });
})
}
但在尝试添加重复值时返回Unhandled Rejection (TypeError): Cannot read property 'carNumber' of undefined
。为避免错误,更新错误功能以验证undefined
值:
export const addCar = (req, res) => {
const newCar = new Car(req.body);
newCar.save((err, car) => {
if (car.carNumber === undefined) {
return res.json({ 'success': false, '': 'Some Error' });
}
else {
return res.json({ 'success': true, 'message': 'Car '+ car.carNumber +' added successfully', car });
}
})
}
但是在前端redux操作中Unhandled Rejection (SyntaxError): Unexpected token P in JSON at position 0
处response.json().then(error => { ... }
:
export const addNewCar = (car) => {
console.log(car)
return (dispatch) => {
dispatch(addNewCarRequest(car));
return fetch(apiUrl, {
method: 'post',
body: car,
}).then(response => {
if (response.ok) {
response.json().then(data => {
console.log(data.car);
dispatch(addNewCarRequestSuccess(data.car, data.message))
})
}
else {
response.json().then(error => {
dispatch(addNewCarRequestFailed(error))
})
}
})
}
}
感觉完全失去了......可能有人遇到了同样的问题?
答案 0 :(得分:1)
正如评论中所述,我认为您.then()
而不是json()
上有fetch()
。你需要一些形状:
export const addNewCar = car => {
console.log(car);
return dispatch => {
dispatch(addNewCarRequest(car));
return fetch(apiUrl, {
method: "post",
body: car
})
.then(response => {
if (response.ok) {
return response.json();
} else {
throw Error('blah')
}
})
.then(data => {
console.log(data.car);
dispatch(addNewCarRequestSuccess(data.car, data.message));
})
.catch(error => {
dispatch(addNewCarRequestFailed(error));
});
};
};