【发布时间】:2021-01-13 06:09:22
【问题描述】:
我有一个在 localhost:8080 上运行的前端 Vue 应用程序。我正在尝试向运行在 localhost:1337 上的后端应用程序(即 Sails JS 节点应用程序)发送请求。
我的 Vue 应用程序的请求代码如下所示:
actions/index.vue
async testFetch() {
await fetch('http://localhost:1337/recipe', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
displayName: 'test',
}),
});
}
根据 Chrome devtools,请求似乎正在正确发送。复制为 CURL:
curl 'http://localhost:1337/recipe' \
-H 'Connection: keep-alive' \
-H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36' \
-H 'Content-Type: application/json' \
-H 'Accept: */*' \
-H 'Origin: http://localhost:8080' \
-H 'Sec-Fetch-Site: same-site' \
-H 'Sec-Fetch-Mode: cors' \
-H 'Sec-Fetch-Dest: empty' \
-H 'Referer: http://localhost:8080/' \
-H 'Accept-Language: en-US,en;q=0.9' \
--data-binary '{"displayName":"test"}' \
--compressed
我的后端应用程序是使用 Sails JS CLI 版本 1.4.0 创建的 Sails JS 节点应用程序。我运行了命令sails new 并选择了webapp 选项。我使用sails lift 运行应用程序。
我相信我有适合 Sails 应用的 CORS 设置。无论如何,在我设置 CORS 设置之前,我在前端遇到了 CORS 错误,现在我没有了。
backend/config/security.js
module.exports.security = {
cors: {
allRoutes: true,
allowOrigins: ['http://localhost:8080'],
},
csrf: false
};
为了减少调试中的变量,我暂时禁用了csrf。
根据Sails JS documentation,如果我启用了 REST 蓝图,那么当我创建模型时,应该会自动为其创建路由和操作(如果服务器被拆除并使用 sails lift 重新启动) .我相信我有适当的配置来启用此功能:
backend/config/blueprints.js
module.exports.blueprints = {
actions: false,
rest: true,
shortcuts: false,
};
我相信我已经正确地建立了一个模型,所以 Sails 应该为该模型创建一个蓝图路线和蓝图动作:
后端/api/models/Recipe.js
module.exports = {
attributes: {
displayName: {
type: 'string',
required: true,
example: 'Mamas puddin',
},
},
};
据我所知,backend/api/controllers 中没有冲突的操作或控制器。另外,据我所知,backend/config/routes.js 中没有冲突的路线。我在 Chrome devtools 中看到的回复是“未经授权”,状态码为401。运行sails lift 的终端显示<- POST /recipe。如果我向不同的路由发送请求,例如 /foo/bar,我会得到 404。此外,如果我将浏览器导航到 localhost:1337(而不是简单地将 Sails JS 应用程序用作 API),默认 Sails JS webapp 功能正常。
如何在 Sails JS 应用上向蓝图路由发送 XHR 请求?
【问题讨论】:
-
允许的来源,没有列出 localhost:1337
-
Sails JS 配置下允许的来源? Sails JS 服务器托管在 :1337 端口下,但我将尝试添加它只是为了看看。
-
我将 :1337 添加到 allowOrigins 数组中,但仍然有同样的错误。
标签: javascript node.js sails.js