【问题标题】:Calling a not CORS enabled API from node or react从节点调用未启用 CORS 的 API 或做出反应
【发布时间】:2018-08-28 02:43:50
【问题描述】:

我正在尝试从 React 应用程序或节点后端调用 MicroStrategy API,但我收到 401 未经授权的错误。

在 postman 或 chrome 中运行时(只需将 url 粘贴到地址栏中),我会收到带有访问令牌的状态 200 响应。然后 Postman 生成以下 nodejs 代码:

var request = require("request");

var options = { method: 'GET',
  url: 'http://*/MicroStrategy/asp/TaskAdmin.aspx',
  qs: 
   { taskId: 'getSessionState',
     taskEnv: 'xml',
     taskContentType: 'xml',
     server: '*',
     project: '*',
     uid: '*',
     pwd: '*' },
  headers: 
   { 'postman-token': '9c7f6ca8-1ae4-b296-17cf-d850369cbad4',
     'cache-control': 'no-cache' } };

request(options, function (error, response, body) {
  if (error) throw new Error(error);

  console.log(body);
});

此代码导致 401 错误。

当从客户端尝试相同的操作(使用 react 和 axios)时,chrome 会抛出以下错误:

No 'Access-Control-Allow-Origin' header is present on the requested 
resource. Origin 'http://localhost:3000' is therefore not allowed access. 
The response had HTTP status code 401.

问题不是浏览器阻止了 CORS,而是 MicroStrategy 服务器阻止了请求,可能是因为它有一个“Origin”标头。有没有办法在节点中发出与邮递员完全相同的请求?

【问题讨论】:

  • 我认为这是由于缺少 CORS 而导致的网页阻塞,因为您可以在 chrome 上看到它

标签: node.js reactjs cors microstrategy


【解决方案1】:

跨源资源共享 (CORS) 是一种机制,它使用额外的 HTTP 标头让用户代理获得访问来自与当前使用的站点不同源(域)的服务器上的选定资源的权限。

您收到错误是因为您使用了不同的域、端口或协议。如果要解决此问题,则必须在响应中添加响应标头。 试试下面的代码可能会有所帮助

const app = express();

app.use("/api/*", function (request, response, next) {
response.setHeader('Access-Control-Allow-Origin', '*');
}

【讨论】:

  • 资源是一个 iis 服务器。我发现它可以在 chrome 中工作,因为它所做的 Windows 身份验证是背景。响应头如下: {"server":"Microsoft-IIS/8.5","www-authenticate":"Negotiate, NTLM","x-powered-by":"ASP.NET","date": "Tue, 20 Mar 2018 07:48:42 GMT","connection":"close","content-length":"0"} 可能我需要配置 iis 以允许未经身份验证的请求。
猜你喜欢
  • 2022-11-12
  • 2019-03-01
  • 1970-01-01
  • 2020-08-24
  • 1970-01-01
  • 1970-01-01
  • 2018-01-13
  • 1970-01-01
  • 2021-03-18
相关资源
最近更新 更多