用Node.js编写的服务器返回以下错误消息:
TypeError: Cannot read property 'save' of undefined
at e:\_Angular5\administration\routes\product.js:34:12
at e:\_Angular5\administration\node_modules\mongoose\lib\model.js:3930:16
at (anonymous function).call (e:\_Angular5\administration\node_modules\mongoose\lib\query.js:3018:9)
at model.Query.Query._findOne (e:\_Angular5\administration\node_modules\mongoose\lib\query.js:1497:12)
at model.Query.Query.findOne (e:\_Angular5\administration\node_modules\mongoose\lib\query.js:1611:8)
我的服务器代码server.js:
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const http = require('http');
const app = express();
var user = require('./routes/user.js');
var product = require('./routes/product.js');
const api = require('./server/api');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));
app.use(function(req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, Access-Control-Allow-Credentials");
res.setHeader("Access-Control-Allow-Credentials", "true");
next();
});
app.use(express.static(path.join(__dirname, 'dist')));
app.post('/register', user.signup);
app.post('/login', user.login);
app.get('/user/:id', user.getuserDetails);
app.put('/user/:id', user.updateUser);
app.post('/user/products/:id', product.saveproduct); // did not work
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
const port = process.env.PORT || '4200';
app.set('port', port);
const server = http.createServer(app);
server.listen(port, () => console.log(`Running on localhost:${port}`));
路由/ product.js:
var mongoose = require( 'mongoose' );
var Product = require('../models/products');
var config = require('../server/config');
exports.saveproduct = function(req, res, next){
const userid = req.params.id;
const product_name = req.body.product_name;
const product_type = req.body.product_type;
const product_desc = req.body.product_desc;
const expid = req.body.expid;
if (!userid || !product_name || !product_type || !product_desc) {
return res.status(422).send({ success: false, message: 'Posted data is not correct or incompleted.' });
} else {
if (userid) {
Product.findById({product_name: req.body.product_name} ).exec(function(err, product){
if(err){ res.status(400).json({ success: false, message: 'Error processing request '+ err }); }
if(product) {
product.product_name = product_name;
product.product_type = product_type;
product.product_desc = product_desc;
}
product.save(function(err) {
if(err){ res.status(400).json({ success: false, message: 'Error processing request '+ err }); }
res.status(201).json({
success: true,
message: 'product updated successfully'
});
});
});
}else{
let oProduct = new Product({
userid: uid,
product_name: product_name,
product_type: product_type,
product_desc: product_desc
});
oProduct.save(function(err) { // error
if(err){ res.status(400).json({ success: false, message: 'Error processing request '+ err }); }
res.status(201).json({
success: true,
message: 'Product saved successfully'
});
});
}
}
}
的src /应用/产品/用户products.component.ts
@Component({
selector: 'app-user-products',
templateUrl: './user-products.component.html',
styleUrls: ['./user-products.component.css']
})
export class UserProductsComponent implements OnInit {
user: User;
UserType = UserType;
product_name: string;
product_type: ProductType;
ProductType = ProductType;
product_desc: string;
produktForm: FormGroup;
products: Product;
userObj: any;
productid: string;
constructor(private fb: FormBuilder,
private route: ActivatedRoute,
private router: Router,
private productsService: ProductsService,
private authService: AuthService) { }
ngOnInit() {
this.userObj = this.authService.currentUser;
this.route.params.subscribe((params: any) => {
if (params.id) {
console.log('params.id : ');
console.log(params.id);
this.productid = params['_id'];
console.log('this.productid : ');
console.log(this.productid);
}
});
this.produktForm = this.fb.group({
product_name: ['', Validators.required],
product_type: ['', Validators.required],
product_desc: ['', Validators.required]
});
}
saveProduct(produktForm: any) {
if (this.produktForm.dirty && this.produktForm.valid) {
const theForm = this.produktForm.value;
if (this.productid !== '') {
produktForm.productid = this.productid;
}
this.productsService.add_product(this.userObj.userid, theForm)
.subscribe(data => {
if (data.success === false) {
if (data.errcode) {
this.authService.logout();
this.router.navigate(['login']);
}
console.log('Error ' + data.message);
} else {
console.log('Success ' + data.message);
}
// if (!this.productid) {
this.produktForm.reset();
// }
});
}
}
}
我不知道为什么save方法不起作用。如何纠正错误? 表格发送的数据如下:
{ product_name:“d”, product_type:“1”, product_desc:“d”, productid: undefined}
答案 0 :(得分:1)
if (err) {
res.status(400).json({
success: false,
message: 'Error processing request ' + err
});
}
if (product) {
product.product_name = product_name;
product.product_type = product_type;
product.product_desc = product_desc;
}
product.save(function(err) {
if (err) {
res.status(400).json({
success: false,
message: 'Error processing request ' + err
});
}
res.status(201).json({
success: true,
message: 'product updated successfully'
});
});
您获得的error
是因为您的产品对象是undefined
。您正在检查object
是否存在并分配属性,但在尝试呼叫product.save()
时,您没有检查对象是否存在。
尝试在product.save()
if(product){ }
答案 1 :(得分:0)
有效,下面的解决方案:
var mongoose = require( 'mongoose' );
var Product = require('../models/products');
var config = require('../server/config');
exports.saveproduct = function(req, res, next){
const userid = req.params.id;
const product_name = req.body.product_name;
const product_type = req.body.product_type;
const product_desc = req.body.product_desc;
const expid = req.body.expid;
if (!userid || !product_name || !product_type || !product_desc) {
return res.status(422).send({ success: false, message: 'Posted data is not correct or incompleted.' });
} else {
if (expid) {
Product.findById({product_name: req.body.product_name} ).exec(function(err, product){
if(err){
res.status(400).json({ success: false, message: 'Error processing request '+ err });
}
if(product) {
product.product_name = product_name;
product.product_type = product_type;
product.product_desc = product_desc;
}
product.save(function(err) {
if(err){ res.status(400).json({ success: false, message: 'Error processing request '+ err }); }
res.status(201).json({
success: true,
message: 'product updated successfully'
});
});
});
}else{
let oProduct = new Product({
userid: userid,
product_name: product_name,
product_type: product_type,
product_desc: product_desc
});
oProduct.save(function(err) {
if(err){ res.status(400).json({ success: false, message: 'Error processing request '+ err }); }
res.status(201).json({
success: true,
message: 'Product saved successfully'
});
});
console.log( 'Product saved successfully');
}
}
}