這邊我們先演示後端的部分(明天進行前端範例)
創建sample資料夾,並且在其中輸入以下指令
npm init
下載以下module
npm install express mongoose bcrypt cors dotenv joi
檔案結構如下
製作要存進資料庫的model
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);
module.exports = {
contactModel: require("./contact-model"),
};
透過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;
request路徑處理
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;
module.exports = {
auth: require("./auth"),
};
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.");
});
DB_CONNECT="你的 MongoDB Atlas Application code"
執行時Console會顯示server已運行,並且成功連至MongoDB
【明天將會進行前端的部分】