我想創建一個 post 路由,以便我可以將用戶鍵入的代碼片段存盤到 MongoDB 的集合中。
架構看起來像這樣:-
const newSnippetSchema= new mongoose.Schema({
title:String,
snippet:String
})
簡而言之,我正在創建一個像 codeSandbox 或 code-pen 這樣的網路應用程式,我可以在其中保存用戶已保存或輸入的代碼......我想在觸發 Post Route 時以 Json 格式發送資料
uj5u.com熱心網友回復:
創建一個http post web api。
const express = require('express')
const mongoose = require('mongoose')
const NewSnippetSchema = require('./models/newSnippetSchema')
const app = express()
mongoose.connect('mongodb://localhost/mydb', {
useNewUrlParser: true, useUnifiedTopology: true
})
app.set('view engine', 'ejs')
app.use(express.urlencoded({ extended:false }))
app.post('/newSnippet', async (req, res) => {
await NewSnippetSchema.create({ title: req.body.title, snippet: req.body.snippet })
res.redirect('/')
})
app.listen(process.env.PORT || 5000);
uj5u.com熱心網友回復:
catchAsync 代碼:
const catchAsync = (fn) =>
function asyncUtilWrap(...args) {
const fnReturn = fn(...args);
const next = args[args.length - 1];
return Promise.resolve(fnReturn).catch(next);
};
export default catchAsync;
應用錯誤代碼:
class AppError extends Error {
constructor(message, statusCode) {
super(message);
this.statusCode = statusCode;
this.status = `${statusCode}`.startsWith('4') ? 'fail' : 'error';
this.isOperational = true;
Error.captureStackTrace(this, this.constructor);
}
}
export default AppError;
控制器代碼:
const snippetController = catchAsync(async (req, res, next) => {
const { title, snippet } = req.body;
if (!title || !snippt) {
return next(new AppError('All fields are required', 400));
}
const snippetDoc = await Snippet.create(req.body);
return res.status(201).json({
status: 'success',
snippetDoc
});
});
export default snippetController;
路由器代碼:
router.route('/snippet').post(snippetController);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/332647.html
標籤:javascript json MongoDB 表达 猫鼬
下一篇:如何搜索具有多個屬性的貓鼬資料?
