【发布时间】: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 中。