【问题标题】:rror: SecurityError: Request method not allowed - XMLHTTPRequest - NodeJS错误:安全错误:请求方法不允许 - XMLHTTPRequest - NodeJS
【发布时间】:2018-06-08 04:22:34
【问题描述】:

我正在尝试使用 XMLHTTPRequest 执行获取请求并设置新的请求标头,但是我继续收到 405 错误。它可能是CORS,但我尝试了很多没有运气的东西。

错误:SecurityError:请求方法不允许 我正在使用 NPM 包XMLHTTPRequest

My get request:
const cjURL = 'https:URL';
const cjKey = 'Key'

let header = new Headers();
let xmlRHeader = new  XMLHttpRequest();
xmlRHeader.open().setRequestHeader('authorization', 'value');
header.append('Content-Type', 'application/xml; charset=utf-8');
header.set('autorization', `${this.cjKey}`);
let req = new Request(cjURL, {
  method: 'GET',
  headers: header,
  mode: 'cors'

});


fetch(req)
.then ( (response) => {
  if(response !== null){
    return response;
  } else {
    throw new Error('Bad HTTP Request');
  }
})
.then ( (jsonData) => {
  console.log(jsonData);
})
.catch ((err) => {
  console.log('error', err.message);
});

【问题讨论】:

  • 你为什么要设置header.append('Content-Type', 'application/xml; charset=utf-8');?您正在发出 GET 请求。没有描述内容类型的请求正文。
  • “我正在使用 NPM 包 XMLHTTPRequest”——那么它不太可能是 CORS,因为您没有使用浏览器。
  • 为什么一开始用XMLHttpRequest,然后又放弃改用fetch?这些甚至来自哪里,浏览器提供它们,但 Node.js 没有。
  • 你为什么用api标记这个?标签上写着“请勿使用”!
  • 是的,我现在才开始使用 XMLHTTPRequest。我删除了 API,当我添加它时没有看到。我更关心得到答案,哈哈。我将尝试使用 XMLHTTPRequest。显然我正在使用的 web 服务有一个旧样式的 XML 来提供。我有一个带有 Node JS 后端的 Angular 6 前端。只是试图通过 CORS 并让数据显示在 Angular 中。

标签: node.js xml cors


【解决方案1】:

我终于得到了我需要的请求,而不必担心 CORS。为此,我使用了以下代码:

const cjURL = '网络服务的 URL'

xhr 是分配给 XMLHTTPRequest() 的变量。 您必须使用 open 然后指定方法。在这种情况下,我需要 GET 方法。 如果之后将该方法设置为 true,那么它将使其异步。

接下来,由于我的 Web 服务要求我指定一个 REQUEST 标头。我用 setHRequestHeader 添加了一个请求标头。注意:您只能在 OPEN 之后和 SEND 之前设置请求头。

然后我想从 1-4 检查我的请求的每个状态以检查每个状态的返回。 View all Ready States Here

有关这方面的更多文档,请查看documentation.

const xhr = new XMLHttpRequest();
xhr.open('GET', cjURL, true);

xhr.setRequestHeader('authorization', cjKey)

xhr.onreadystatechange = function (){
  if(this.readyState == 4 && this.status == 200){
   console.log(xhr.responseText);
  } else if (this.readyState == 3){
    console.log('3')
    console.log(xhr.responseText);
  } else if (this.readyState == 2){
    console.log('2')
    console.log(xhr.responseText);
  } else if (this.readyState == 1){
    console.log('1')
    console.log(xhr.responseText);
  } 
}

xhr.send();

【讨论】:

    猜你喜欢
    • 2018-05-24
    • 2014-01-08
    • 2021-08-16
    • 2020-03-05
    • 2021-04-05
    • 2021-09-11
    • 2013-10-10
    • 2019-01-22
    • 1970-01-01
    相关资源
    最近更新 更多