对于我的React / Express应用程序,我已经在Express中构建了我的后端API,包括发布博客文章(/ api / posts)的途径。在前端,我用提交此路由的POST方法构建了一个表单,但是在提交表单时出现错误“ Cannot POST / api / posts”。
app.js(Express)
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const session = require('express-session');
const app = express();
//Load routes
const photos = require('./routes/photos');
const posts = require('./routes/posts');
const recs = require('./routes/recs');
// DB config
const db = require('./config/database');
//Connect to mongoose
mongoose.connect(db.mongoURI, {useNewUrlParser: true})
.then(() => console.log('MongoDB connected...'))
.catch(err => console.log(err));
// Body parser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
// Static folder
app.use(express.static(path.join(__dirname, 'public')));
// Express Session Middleware
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true,
//cookie: {secure: true}
}));
//Router
app.use('/api/photos', photos);
app.use('/api/posts', posts);
app.use('/api/posts', recs);
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`Server started on port ${port}`);
});
发布路线
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
// Load Posts model
require('../models/Post');
const Post = mongoose.model('posts')
// Get all posts
router.get('/', (req, res) => {
Post.find()
.sort({date:'desc'})
.then(posts => {
res.json(posts);
})
.catch(err => {
res.send(err);
})
});
router.post('/', (req, res) => {
console.log(req.body); //testing info I receive for now
})
表格
const postForm =
<div className="form-popup" id="newPost">
<form action="/api/posts" method="post" className="form-container">
<h1>New Blog Post</h1>
<label htmlFor="title"><b>Title</b></label>
<input type="text" placeholder="Blog Post Title" name="title" required />
<label htmlFor="location"><b>Location</b></label>
<input type="text" placeholder="Location" name="location" required />
<textarea placeholder="Your post here" name="content" required />
<button type="submit" className="btn">Post</button>
<button type="submit" className="btn cancel" onClick={this.handleClose}>Close</button>
</form>
</div>
答案 0 :(得分:1)
在发布路线的末尾,您必须将其导出。
module.exports = router;
这使您能够像以前一样将其导入app.js。
答案 1 :(得分:1)
根据我们在评论中的交流,这是问题所在
要解决此问题,您只需要将请求的格式设置为http://localhost:5000/api/posts
React
和Node.js
答案 2 :(得分:0)
有两条路由具有相同的端点。
//Router
app.use('/api/photos', photos);
app.use('/api/posts', posts);
app.use('/api/posts', recs);
我认为您希望第三条路线使用不同的终点。
//Router
app.use('/api/photos', photos);
app.use('/api/posts', posts);
app.use('/api/recs', recs);