首页 > 解决方案 > 使用 post 数据获取 expressjs 导致找不到 404 服务器

问题描述

用我自己的 expressjs api 后端有一个反应前端。Express v. 4.16.0

在反应前端使用 fetch 来获取数据就可以了。

 fetch('/desResData')
      .then(res => {....}

当我尝试使用请求发布一些数据时,我得到:“POST http://localhost:3000/desResData 404(未找到)”代码:

 fetch('/desResData',
      {
        method: 'POST',
        body: { product: "test" }, // tried JSON.stringify as well
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        }
      }
    )
      .then(res => {....}

粗略地说,我可以从前端到后端进行静态通信,但我无法参数化我的请求。

ExpressJS:

router.get('/', async function (req, res, next) {

  console.log(req.body) // tried with using req and without using it

  findByProduct("product") // some async db operation // this part is working fine while fetching without any post parameters
    .then(data => {
       res.json()
      })

标签: javascriptnode.jsreactjsexpress

解决方案


您必须编写router.post(不是router.get)来处理 HTTP POST 请求。

请注意您的 fetch方法POST. 但是你写了which 处理方法所在router.get的请求。GET

如果对不存在的路由发出 POST 请求,express 将给出 404。即使有相同路由的 GET 处理程序,这也适用。

.get(提示:您可以使用, .post, .put,等为同一路由拥有单独的 GET、POST、PUT、DELETE 等处理程序.delete。)


推荐阅读