iT邦幫忙

2022 iThome 鐵人賽

DAY 28
0
Modern Web

30天全端網頁學習之旅系列 第 28

範例練習(後端)

  • 分享至 

  • xImage
  •  

這邊我們先演示後端的部分(明天進行前端範例)

創建sample資料夾,並且在其中輸入以下指令

npm init

下載以下module

npm install express mongoose bcrypt cors dotenv joi

檔案結構如下
https://ithelp.ithome.com.tw/upload/images/20221011/20152607uOl1nT6VoZ.png

models

製作要存進資料庫的model

models/contact-model.js

const mongoose = require("mongoose");

const contactSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
  },
  phone: {
    type: String,
    required: true,
  },
  need: {
    type: String,
    required: true,
  },
  date: {
    type: Date,
    default: Date.now,
  },
});

module.exports = mongoose.model("Contact", contactSchema);

models/index.js

module.exports = {
  contactModel: require("./contact-model"),
};

validation.js

透過joi驗證要處存的數據是否有效

const Joi = require("joi");

const contactValidation = (data) => {
  const schema = Joi.object({
    name: Joi.string().required(),
    email: Joi.string().required().email(),
    phone: Joi.string().required(),
    need: Joi.string().required(),
  });

  return schema.validate(data);
};

module.exports.contactValidation = contactValidation;

routes

request路徑處理

routes/auth.js

const router = require("express").Router();
const contactValidation = require("../validation").contactValidation;
const contact = require("../models").contactModel;

router.use((req, res, next) => {
  console.log("A request is coming in to auth.js");
  next();
});

router.get("/testAPI", (req, res) => {
  const msgObj = {
    message: "Test API is working.",
  };
  return res.json(msgObj);
});

router.post("/method", async (req, res) => {
  console.log("contact!!!");
  const { error } = contactValidation(req.body);
  if (error) return res.status(400).send(error.details[0].message);

  const newContact = new contact({
    name: req.body.name,
    email: req.body.email,
    phone: req.body.phone,
    need: req.body.need,
  });

  try {
    const savedContact = await newContact.save();
    res.status(200).send({
      message: "success",
      savedobject: savedContact,
    });
  } catch (err) {
    res.status(400).send("Contact not saved.");
  }
});

module.exports = router;

routes/index.js

module.exports = {
  auth: require("./auth"),
};

index.js

const express = require("express");
const app = express();
const mongoose = require("mongoose");
const dotenv = require("dotenv");
dotenv.config();
const authRoute = require("./routes").auth;
const cors = require("cors");

mongoose
  .connect(process.env.MONGODB_URL || process.env.DB_CONNECT, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then(() => {
    console.log("Connect to Mongo Altas");
  })
  .catch((e) => {
    console.log(e);
  });

app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors());
app.use("/api/contact", authRoute);

if (process.env.NODE_ENV === "production") {
  app.use(express.static("client/build"));
}

app.listen(process.env.PORT || 8080, () => {
  console.log("Server running on port 8080.");
});

.env

DB_CONNECT="你的 MongoDB Atlas Application code"

執行時Console會顯示server已運行,並且成功連至MongoDB

【明天將會進行前端的部分】


上一篇
範例練習(介紹)
下一篇
範例練習(前端)
系列文
30天全端網頁學習之旅30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言