javascript - 使用 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 端点,以便可以从外部源直接访问它?
解决方案
不是作为答案,而是为了让我可以格式化并证明必须发生其他事情。这个最小的例子对我来说很好。
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"}
因此,某处肯定发生了其他事情。
推荐阅读
- docker - 带有 React 应用程序的 pod 在 kubernetes 上以 CrashLoopBackOff 状态失败
- python - Python3 包装函数
- javascript - 来自我的网站的发布请求在 Heroku App NodeJS 中不起作用,但来自 localhost 它正在工作
- vba - 在 Word 宏中公开 a 作为新的 Scripting.Dictionary
- postgresql - 为包含名为 id 的列的数据库表创建缺少的序列
- asp.net - 我只能使用 asp.Net 在我的项目上放置 3 个侧面按钮
- r - R Shiny:基于反应数据框的 updateSelectInput
- java - hadoop-hdfs-native 客户端中的 CMAKE-COMPILE 失败
- django-rest-framework - DRF 嵌套序列化程序 - 对象没有属性
- windows - 登录到适用于 Linux 的 Windows 子系统时如何自动运行命令