webpack4+express+mongodb+vue实现增删改查的示例

2020-06-14 06:27:07易采站长站整理

},
editFunc(row) {
this.dialogVisible2 = true;
this._id = row._id;
this.$set(this.$data.update, 'name', row.name);
this.$set(this.$data.update, 'age', row.age);
this.$set(this.$data.update, 'sex', row.sex);
this.row = row;
},
delFunc(row) {
this.dialogVisible3 = true;
console.log(row);
this.row = row;
},
// 编辑页面提交
editConfirm() {
const id = this._id,
name = this.update.name,
age = this.update.age,
sex = this.update.sex;
const obj = {
id: id,
name: name,
age: age,
sex: sex
};
this.$http.post('/api/update', obj).then((res) => {
if (res.ok) {
// 删除成功
this.$message({
message: '更新成功',
type: 'success'
});
// 重新请求下查询
this.query(false);
} else {
// 删除成功
this.$message({
message: '更新失败',
type: 'success'
});
}
this.dialogVisible2 = false;
});
},
// 删除提交
delConfirm() {
const obj = {
'id': this.row._id
};
this.$http.post('/api/del', obj).then((res) => {
console.log(res.body)
if (res.body.ok) {
// 删除成功
this.$message({
message: '删除成功',
type: 'success'
});
// 成功后,触发重新查询下数据
this.query();
} else {
// 删除失败
this.$message({
message: res.body.errorMsg,
type: 'warning'
});
}
this.dialogVisible3 = false;
});
},
// 新增提交
addConfirm() {
// 新增的时候,姓名,年龄,性别 不能为空,这里就不判断了。。。
const obj = {
name: this.add.name,
age: this.add.age,
sex: this.add.sex
};
this.$http.post('/api/add', obj).then((res) => {
console.log(111);
console.log(res);
if (res.body.code === 0) {
this.$message({
message: '新增成功',
type: 'success'
});
// 成功后,触发重新查询下数据
this.query();
} else {
this.$message({
message: res.body.errorMsg,
type: 'warning'
});
}
this.dialogVisible = false;
});
}
}
}
</script>

6. 解决跨域问题,及接口如何访问的?

首先我们是使用express启动的是 http://127.0.0.1:3001 服务器的,但是在我们的webpack中使用的是8081端口的,也就是说页面访问的是http://127.0.0.1:8081/ 这样访问的话,因此肯定会存在接口跨域问题的,因此我们需要在webpack中使用 devServer.proxy 配置项配置一下,如下代码配置:


module.exports = {
devServer: {
port: 8081,