首页 > 解决方案 > 使用 Express 的 Nuxt 应用程序不允许在应用程序外部命中 POST 路由

问题描述

背景

我有一个 NUXT 应用程序,可以按照您的预期呈现 vue 模板。我需要从外部应用程序客户端访问应用程序中的一些 Express 路由。

我可以从外部应用程序中获取 GET 路由,但 POST 请求失败并出现错误 404。

例子

表达

这有效

router.get('/test/get', (req, res, next) => {
  res.json({ message: "Global PDF Generator is configured correctly", status: "operational" })
});

这失败了 404

router.post('/test/post', (req, res, next) => {
  res.json({ message: "Global PDF Generator is configured correctly", status: "operational" })
});

在 Nuxt 应用程序和任何 vue 组件内部,我可以像这样点击 POST 路由,

fetch('api/v1/pdf', { method: 'POST' }

但是如果我们尝试做这样的事情它会失败,

fetch('localhost:3000/api/v1/pdf', { method: 'POST' }

第二个示例很重要,因为显然这就是我必须从外部应用程序到达此应用程序的终点的方式。

我无法弄清楚为什么 GET 请求有效并且没有得到 404,而 POST 请求继续从外部应用程序获取 404。

问题

如何在我的 NUXT 应用程序中创建一个可从外部访问的 Express POST 端点,以便可以从外部源直接访问它?

标签: javascriptnode.jsexpressvue.jsnuxt.js

解决方案


不是作为答案,而是为了让我可以格式化并证明必须发生其他事情。这个最小的例子对我来说很好。

vue init nuxt-community/express-template sample_post
cd sample_post
npm install

修改 api/routes/users.js 添加一个 post 路由:

router.post('/test', function(req, res, next) {
   res.json(message: 'hello');
});

启动服务:

npm run dev

验证它是否成功从外部请求返回帖子:

curl -X POST http://localhost:3000/api/test
{"message":"hello"}

因此,某处肯定发生了其他事情。


推荐阅读