繁体   English   中英

从本地前端应用程序到本地后端 Sails JS 蓝图 REST 路由的 XHR 请求出现 401 错误

[英]Getting 401 error on XHR request from local frontend app to local backend Sails JS Blueprint REST route

我有一个在 localhost:8080 上运行的前端 Vue 应用程序。 我正在尝试向我的后端应用程序发送请求,这是一个在 localhost:1337 上运行的 Sails JS 节点应用程序。

我的 Vue 应用程序的请求代码如下所示:

动作/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 错误,现在我没有了。

后端/配置/security.js

module.exports.security = {
  cors: {
    allRoutes: true,
    allowOrigins: ['http://localhost:8080'],
  },
  csrf: false
};

我暂时禁用了 csrf,以减少调试中的变量。

根据Sails JS 文档,如果我启用了 REST 蓝图,那么当我创建 Model 时,应该会自动为其创建路线和操作(如果服务器被拆除并使用sails lift重新启动)。 我相信我有正确的配置来启用此功能:

后端/配置/blueprints.js

module.exports.blueprints = {
  actions: false,
  rest: true,
  shortcuts: false,
};

我相信我已经正确地建立了一个 Model,所以 Sails 应该为所说的 model 创建蓝图路线和蓝图动作:

后端/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 正常运行。

如何将 XHR 请求发送到 Sails JS 应用程序上的蓝图路由?

我得到 401 的原因是默认的 Sails webapp 有一个策略应用于所有需要它们登录的路由(登录中间件在每条路由上运行),只有少数例外。

为了使用我的蓝图路线,我需要为我的 *action 添加一个例外到这个政策。 (编辑:我相信政策 map 是行动而不是路线。)

后端/配置/policies.js

module.exports.policies = {

  '*': 'is-logged-in',

  // Bypass the `is-logged-in` policy for:
  'entrance/*': true,
  'account/logout': true,
  'view-homepage-or-redirect': true,
  'view-faq': true,
  'view-contact': true,
  'legal/view-terms': true,
  'legal/view-privacy': true,
  'deliver-contact-form-message': true,
  // I needed to add my Model's Blueprint route to the exceptions
  'recipe/*': true,

};

我相信true只是取代了可能的策略 function。无论如何,请求现在成功并带有200代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM