我只是从后端开始,我想部署我的Crud应用程序的后端,但是我陷入了路线困境。在heroku上部署后,我只得到了app.get('/')的一部分。我找不到任何router.get('/ getData'..或router.post('/ updateData'..
这是已部署的heroku链接:
对于app.get('/'):https://vast-beyond-50574.herokuapp.com/
router.get('/ getData):https://vast-beyond-50574.herokuapp.com/getData
对于router.post('/ updateData'):https://vast-beyond-50574.herokuapp.com/updateData
这是后端server.js的代码
const express = require('express');
var cors = require('cors');
const bodyParser = require('body-parser');
const logger = require('morgan');
const Data = require('./data');
const API_PORT = 3001;
const app = express();
app.use(cors());
const router = express.Router();
mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost/backend');
let db = mongoose.connection;
db.once('open', () => console.log('connected to the database'));
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(logger('dev'));
router.get('/getData', (req, res) => {
Data.find((err, data) => {
if (err) return res.json({ success: false, error: err });
return res.json({ success: true, data: data });
});
});
router.post('/updateData', (req, res) => {
const { id, update } = req.body;
Data.findByIdAndUpdate(id, update, (err) => {
if (err) return res.json({ success: false, error: err });
return res.json({ success: true });
});
});
router.delete('/deleteData', (req, res) => {
const { id } = req.body;
Data.findByIdAndRemove(id, (err) => {
if (err) return res.send(err);
return res.json({ success: true });
});
});
router.post('/putData', (req, res) => {
let data = new Data();
const { id, message } = req.body;
if ((!id && id !== 0) || !message) {
return res.json({
success: false,
error: 'INVALID INPUTS',
});
}
data.message = message;
data.id = id;
data.save((err) => {
if (err) return res.json({ success: false, error: err });
return res.json({ success: true });
});
});
app.get('/', (req, res) => {
res.send('Deployed!');
});
app.use('/api', router);
const PORT = process.env.PORT || 3000
app.listen(PORT, () => console.log(`LISTENING ON PORT ${PORT}`));```
答案 0 :(得分:0)
您正在/api
路由(app.use('/api', router);
)内使用路由器,这意味着所有这些路由都将以/api
为前缀。因此,您应该可以访问https://vast-beyond-50574.herokuapp.com/api/getData
并查看数据。 (但是,我尝试了此操作,但遇到了另一个错误,您将不得不单独调试它。)