【问题标题】:Node/Express Cannot POST error (React frontend)Node/Express 无法 POST 错误(反应前端)
【发布时间】:2019-02-20 06:44:50
【问题描述】:

对于我的 React/Express 应用程序,我已经在 Express 中构建了我的后端 API,包括用于发布博客文章 (/api/posts) 的路由。在前端,我使用 POST 方法构建了一个表单,该方法提交到此路由,但是当我提交表单时,我收到错误“无法 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>

【问题讨论】:

  • 你可以通过邮递员访问API吗?
  • @DanPhilip 不,我在那里遇到了同样的错误。我不知道为什么,因为我在另一个我已经完成的项目上对这个 API 进行建模。我不应该同时向 /api/posts 发送 get 和 post 请求吗?
  • 你能补充一下你是如何提出请求的吗?
  • @molamk 在邮递员中?我正在向 localhost:3000/api/posts 发送一个 POST 请求,正文字段为 title: test 和 location: thailand
  • 这就是问题所在。您在端口 3000 上发送,但在端口 5000 上侦听

标签: node.js reactjs express post


【解决方案1】:

根据我们在评论中的交流,这就是问题所在

  • 请求被发送到端口 3000
  • Node.js 服务器正在侦听端口 5000

要解决这个问题,您只需将请求格式化为http://localhost:5000/api/posts

注意事项

  • 您仍然需要在不同的端口上运行 ReactNode.js
  • 您只需更改 HTTP 请求的端口

【讨论】:

  • 如果这是真的,将不会出现错误“Cannot POST /api/posts”。
  • 怎么样? React 默认在端口 3000 上运行,它不支持 /api/posts 路由上的 POST 请求。消息有效
  • hm,我认为如果他收到此错误,则表示他可以连接到服务器,但在服务器上找不到路由。如果出现这样的连接错误,请求就会超时而没有收到任何响应。
  • 这实际上是错误的。 React 捕获请求并返回Cannot POST /api/posts。您可以自己尝试一下,[这里有一个链接,您可以尝试一下]
  • @molamk 所以为了确保我理解,在我的表单中,我会将操作更改为“/api/posts:5000”?这也适用于生产环境吗?
【解决方案2】:

在 Post Route 结束时,您必须将其导出。

module.exports = router;

这使您能够像以前一样在 app.js 中导入它。

【讨论】:

    【解决方案3】:

    有两条具有相同端点的路由。

    //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);
    

    【讨论】:

    • 是的。但这并不能解决问题,因为在原始情况下,/api/posts 上的第一个路由器被调用
    • 感谢您的关注!但是,当我发布时它仍然抛出同样的错误。
    【解决方案4】:

    表单上的action路由与服务器端的post路由不匹配。

    <form action="/api/posts" method="post" className="form-container">
    
    router.post('/', (req, res) => {
    

    action 路由应该与 post 路由匹配才能使 post 动作起作用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-24
      • 2019-07-23
      • 2014-05-10
      • 1970-01-01
      • 2021-10-24
      • 1970-01-01
      相关资源
      最近更新 更多