gpt4 book ai didi

node.js - 无法读取未定义 Angular 的属性 'save'

转载 作者:太空宇宙 更新时间:2023-11-04 00:11:13 25 4
gpt4 key购买 nike

用 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}`));

routes/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/app/product/user-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();
// }
});
}
}
}

我不知道为什么保存方法不起作用。犯了错误如何改正?表单发送的数据如下:

{产品名称:“d”,产品类型:“1”,产品描述:“d”,产品 ID:未定义}

最佳答案

 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'
});
});

您收到的错误是因为您的产品对象未定义。您正在检查您的对象是否存在并分配属性,但在尝试调用product.save()时您没有检查您的对象是否存在。

尝试在 if(product){ }

中嵌套 product.save()

关于node.js - 无法读取未定义 Angular 的属性 'save',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49450415/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com