【问题标题】:Nuxt application using Express won't allow POST routes to be hit externally of application使用 Express 的 Nuxt 应用程序不允许在应用程序外部命中 POST 路由
【发布时间】:2018-11-12 03:33:47
【问题描述】:

背景

我有一个 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 端点,以便可以从外部源直接访问它?

【问题讨论】:

  • 您是否在为您的发布路线使用某种解析器?
  • fetch 将使用 GET 除非您添加方法参数 -- fetch('localhost:3000/api/v1/pdf', { method: 'POST'})
  • 是的,当然,我正在使用 POST。
  • @EdwinDelRio 我没有使用任何特别的东西。如您所见,问题中的这两条测试路线非常简单。我可以在外部点击get,但不能点击POST。例如,如果我现在尝试在 Postman 中点击 POST 路由,它将失败。
  • 您使用的是http 还是https?你试过fetch('http://localhost:3001/...')

标签: javascript node.js express vue.js nuxt.js


【解决方案1】:

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

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"}

所以某处肯定发生了其他事情。

【讨论】:

    【解决方案2】:

    这是因为当 NuxtJs 应用程序投入生产时,它只看到页面 routes 而不是服务器 route。你应该使用 NuxtJs serverMiddleware。你可以从 NuxtJs API 找到它here

    【讨论】:

      猜你喜欢
      • 2020-08-01
      • 2019-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-17
      • 2019-09-01
      • 1970-01-01
      相关资源
      最近更新 更多