我是nodejs的新手。我刚刚使用Nodejs,Hbs,mongoose和express创建了一个CRUD项目。在localhost上测试更新功能时。错误:Cannot GET /api/course/update/:courseId
我以前试过用POSTMAN测试API。但一切都很好。下面是我的代码:
Server.js
const express = require('express');
const handlebars = require('handlebars');
const exphbs = require('express-handlebars');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const {allowInsecurePrototypeAccess} = require("@handlebars/allow-prototype-access")
const dbConfig = require('./APP/config/db.config');
const app = express();
app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())
const db = require('./APP/models');
const Role = db.role;
db.mongoose
.connect(`${dbConfig.URL}`, {
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(() => {
console.log("Successfully connected to the database");
initial();
}).catch(err => {
console.log('Could not connect to the database. Exiting now...', err);
process.exit();
});
app.engine('hbs', exphbs({
handlebars: allowInsecurePrototypeAccess(handlebars),
defaultLayout: 'main',
extname: '.hbs',
layoutsDir: __dirname + '/VIEWS/layouts/'
}));
app.set('view engine','hbs');
app.get('/', (req, res) => {
res.render('home',{msg:'This is home page'})
});
require('./APP/routes/auth.routes')(app);
require('./APP/routes/component.routes')(app);
require('./APP/routes/main.routes')(app);
app.listen(1000, () => {
console.log('Server is running 1000');
})
component.routes.js
const controller = require('../controllers/component.controller');
const service = require('../routes/index');
module.exports = function (app) {
app.get('/about-us', service.about_us);
app.get('/main-course', service.main_course);
app.get('/add-course', service.add_course);
route.get('/update-course/:courseId', service.update_course)
route.get('/detail-course', service.detail_course)
//API
app.get('/api/course/findAll',controller.findAll)
app.post('/api/course/create', controller.createCourse)
app.put('/api/course/update/:courseId', controller.updateCourse)
app.delete('/api/course/delete/:courseId',controller.deleteCourse)
}
component.controller.js
const db = require("../models")
const Course = db.course;
exports.updateCourse = function(req, res){
if (!req.body.name) {
return res.status(400).send({message: "Data to update can not be empty"})
}
const courseId = req.params.courseId;
Course.findByIdAndUpdate(courseId, {
name: req.body.name,
// creationTime: new Date().getTime(),
creationTime: req.body.creationTime,
description: req.body.description
},{useFindAndModify : false})
.then(course => {
if (!course) {
return res.status(404).send({message: "Course not found with id"});
}
res.send(course)
}).catch(err => {
return res.status(500).send({message: "Error retrieving note with id"});
});
}
我做错了什么,我该如何改正?
1条答案
按热度按时间shyt4zoc1#
您需要对更新端点执行PUT而不是GET。PUT方法可以在postman中的URL之前选择(GET / POST / PUT / DELETE /....etc)