【问题标题】:Fetch with post data to expressjs leads to 404 server not found使用 post 数据获取 expressjs 导致找不到 404 服务器
【发布时间】:2019-05-31 12:06:34
【问题描述】:

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

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

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

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

 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()
      })

【问题讨论】:

  • 快递代码长什么样?
  • 你的后端代码是什么?你用的是快递'.post(...)?

标签: javascript node.js reactjs express


【解决方案1】:

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

请注意,您获取的方法是POST。但是你写了router.get,它处理方法是GET的请求。

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

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

【讨论】:

  • 哦,男孩,这是一些非常基本的东西.....解决了这个问题,收到了一些新的警告,但至少我的信息正在通过 :) 非常感谢!
【解决方案2】:

将此添加到您的服务器代码中:

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS, HEAD');
    next();
});

在你的反应代码的 package.json 中:

"proxy": "http://localhost:serverport",  <-- server port will be port of your node-express server

【讨论】:

  • 代理已经设置,添加标题选项对我不起作用。
猜你喜欢
  • 2016-08-04
  • 1970-01-01
  • 2019-10-17
  • 2021-02-12
  • 1970-01-01
  • 2017-04-26
  • 1970-01-01
  • 2016-10-24
  • 1970-01-01
相关资源
最近更新 更多