使用 Express 的 Nuxt 应用程序不允许 POST 路由在应用程序外部被命中
Nuxt application using Express won't allow POST routes to be hit externally of application
背景
我有一个 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 端点,以便它可以直接从外部源访问?
不是作为答案,而是为了让我可以格式化事物并证明必须进行其他操作。这个最小的例子对我来说很好用。
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
从外部请求成功验证returns post:
curl -X POST http://localhost:3000/api/test
{"message":"hello"}
所以一定有其他事情发生了。
这是因为当 NuxtJs 应用程序投入生产时,它只能看到页面 routes
而不是服务器 route
。你应该使用 NuxtJs serverMiddleware
。你可以从 NuxtJs API
中找到它 here
背景
我有一个 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 端点,以便它可以直接从外部源访问?
不是作为答案,而是为了让我可以格式化事物并证明必须进行其他操作。这个最小的例子对我来说很好用。
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
从外部请求成功验证returns post:
curl -X POST http://localhost:3000/api/test
{"message":"hello"}
所以一定有其他事情发生了。
这是因为当 NuxtJs 应用程序投入生产时,它只能看到页面 routes
而不是服务器 route
。你应该使用 NuxtJs serverMiddleware
。你可以从 NuxtJs API