文章主要記錄如何實現使用express鏈接數據庫,作增刪改查,關聯數據庫,封裝路由,jsonwebtoken鑑權,bcrypt登陸密碼加密,multer文件上傳和一些請求數據的處理,開發日誌記錄。javascript
api/middleware/check-auth.jsjava
const jwt = require('jsonwebtoken');
module.exports = (req, res, next) => {
try {
const token = req.headers.authorization.split(" ")[1];
const decoded = jwt.verify(token, 'secret');
req.userData = decoded;
next();
} catch (error) {
return res.status(401).json({
message: 'Auth failed'
});
}
}
複製代碼
// 接受一個以 productImage 命名的文件。這個文件的信息保存在 req.file。
// 加上checkAuth做爲中間鑑權
router.post('/', checkAuth, uploads.single('productImage'), (req, res, next) => {
console.log(req.file)
const product = new Product({
_id: new mongoose.Types.ObjectId(),
name: req.body.name,
price: req.body.price,
productImage: req.file.path
});
product
.save()
.then(result => {
res.status(201).json({
message: "created product successfully",
createdProduct: {
name: result.name,
price: result.price,
_id: result._id,
productImage: result.productImage,
request: {
type: 'GET',
url: 'http://localhost:3000/products/' + result._id
}
}
})
})
.catch(err => {
res.status(500).json({
error: err
})
})
})
複製代碼
僅僅是productImage命名的文件才能夠node
{
// 使用 IntelliSense 瞭解相關屬性。
// 懸停以查看現有屬性的描述。
// 欲瞭解更多信息,請訪問: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "nodemon",
"runtimeExecutable": "nodemon",
"args": ["${workspaceRoot}/server.js"],
"restart": true,
"protocol": "inspector", //至關於--inspect了
"sourceMaps": true,
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
}
]
}
複製代碼