繁体   English   中英

使用快速服务器的 POST 请求出现 404 错误

[英]404 error with POST request using express server

我正在运行这个 function 应该将数据发布到我的快递服务器。 单击按钮时会调用 function。

const fetchData = async () => {
    const response = await fetch('http://localhost:1337/api/test', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        message: 'hello world'
      }),
    })

    // const data = await response.json()
    const data = await response
    console.log(data)
  }

这是我的快速配置

const express = require('express')
const cors = require('cors')

const app = express()
app.use(cors())
app.use(express.json())

app.get('/api/test', (req: any, res: any) => {
  console.log(req.body)
  res.json({ status: 'ok' })
})

app.listen(1337, () => {
  console.log('Server started on 1337')
})

问题是,当我单击按钮时,我收到 POST 请求的 404 错误,并且我的console.log(response)结果如下。

Response { type: "cors", url: "http://localhost:1337/api/test", redirected: false, status: 404, ok: false, statusText: "Not Found", headers: Headers, body: ReadableStream, bodyUsed: false }
​
body: ReadableStream { locked: false }
​
bodyUsed: false
​
headers: Headers {  }
​
ok: false
​
redirected: false
​
status: 404
​
statusText: "Not Found"
​
type: "cors"
​
url: "http://localhost:1337/api/test"
​
<prototype>: ResponsePrototype { clone: clone(), arrayBuffer: arrayBuffer(), blob: blob(), … }

您正在从客户端发出 POST 请求,但没有在服务器端配置 POST 请求处理程序。 相反,您有一个 GET 请求处理程序。 解决方案是为 POST 请求添加处理程序或将 POST 请求方法转换为 GET。

您没有从 fetchData function 返回响应。 您应该简单地返回如下响应。 -服务器端也没有发布请求处理程序。 您可以添加为获取请求编写的发布请求处理程序。

const fetchData = async () => {
const response = await fetch('http://localhost:1337/api/test', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    message: 'hello world'
  }),
})

// const data = await response.json()
const data = await response
//need to return response as below
 return data.json();

}

在后端将 app.get 更改为 app.post

const express = require('express')
const cors = require('cors')

const app = express()
app.use(cors())
app.use(express.json())

// here
app.post('/api/test', (req: any, res: any) => {
  console.log(req.body)
  res.json({ status: 'ok' })
})

app.listen(1337, () => {
  console.log('Server started on 1337')
})

在您尚未实现 POST 端点的服务器中,您仅实现了 GET 端点

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM