我是nodejs的新手。我刚刚创建了一个CRUD项目使用Nodejs, Hbs,猫鼬和express。在本地主机上测试更新功能时。我得到了错误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"});
});
}
我做错了什么,我该如何改正?
需要对更新端点执行PUT操作,而不是GET操作。可以在URL (GET/POST/PUT/DELETE/....)之前选择POST方法等)