我正在尝试从反应应用程序或节点后端调用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'标头。有没有办法在节点中制作与邮递员完全相同的请求?
答案 0 :(得分:0)
跨源资源共享(CORS)是一种机制,它使用其他HTTP标头让用户代理获得从与当前正在使用的站点不同的源(域)上的服务器访问所选资源的权限。
您因为使用不同的域或端口或协议而收到错误。如果要解决此问题,则必须添加响应标头作为响应。 尝试下面的代码可能会有所帮助
const app = express();
app.use("/api/*", function (request, response, next) {
response.setHeader('Access-Control-Allow-Origin', '*');
}