Vue+Mongoose+node往mongodb数据库添加数据(仅添加)


样式用的是vant

1.文件结构

2.App.vue





3.main.js

import Vue from "vue";
import App from "./App.vue";
import Vant from "vant";
import axios from "axios";
import "vant/lib/index.css";

Vue.use(Vant);

Vue.prototype.$http = axios;
Vue.config.productionTip = false;

new Vue({
  render: (h) => h(App),
}).$mount("#app");

4.app.js

const express = require("express");
const app = new express();
const User = require("./model/user");

var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.post("/data/user", async (req, res) => {
  console.log(req.body);
  const user = new User(req.body);
  const result = await user.save();
  if (result) {
    res.json({
      code: 200,
      msg: "添加成功",
    });
  } else {
    res.json({
      code: 201,
      msg: "添加失败",
    });
  }
});
app.listen(8888, "127.0.0.1");

5.user.js

const mongoose = require("mongoose");

mongoose.connect("mongodb://localhost:27017/20201210", { useNewUrlParser: true, useUnifiedTopology: true });

const Schema = mongoose.Schema;

const userSchema = new Schema({
  username: String,
  password: String,
});

const User = mongoose.model("User", userSchema);
module.exports = User;

6.vue.config.js(跨域配置)

// module.exports = {
//   lintOnSave: false,
// };
const path = require("path");

module.exports = {
  // 部署应用包时的基本 URL,用法和 webpack 本身的 output.publicPath 一致
  publicPath: "./",
  // 输出文件目录
  outputDir: "dist",
  // eslint-loader 是否在保存的时候检查
  lintOnSave: true,
  // 是否使用包含运行时编译器的 Vue 构建版本
  runtimeCompiler: false,
  // 生产环境是否生成 sourceMap 文件
  productionSourceMap: false,
  // 生成的 HTML 中的