javascript - 使用 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()
})
解决方案
您必须编写router.post
(不是router.get
)来处理 HTTP POST 请求。
请注意您的 fetch方法是POST
. 但是你写了which 处理方法所在router.get
的请求。GET
如果对不存在的路由发出 POST 请求,express 将给出 404。即使有相同路由的 GET 处理程序,这也适用。
.get
(提示:您可以使用, .post
, .put
,等为同一路由拥有单独的 GET、POST、PUT、DELETE 等处理程序.delete
。)
推荐阅读
- python - 如何隐藏 QFileSystemModel 上的文件扩展名
- node.js - 如果未找到 Id,Mongoose findByIdAndUpdate 不会返回错误
- rust - 如何制作递归宏来分解此代码?
- vb.net - 如何从 VB .Net 表单应用程序访问 Google Datastore LocalStructuredProperty?VB 将其视为一个 blob
- azure - Azure VMSS 缩减策略不允许我为缩减规则设置超过 60 分钟的冷却时间
- python - 在 python/javascript/shell 中打开带有 Windows 64 位附件的 Outlook
- powerbi - 使用免费试用帐户将 Power BI 发布到 Web
- java - 在java中将(n)的最后一个字符更改为另一个字符
- php - 是否有更好的方法来对包含各种语言字符串的数组进行排序
- audio - ffmpeg 从 .ts 文件中仅提取 1 个音频流的一部分