我正在尝试从HP Alm的REST API中获取一些数据.它适用于小卷曲脚本 - 我得到了我的数据.
现在使用JavaScript,fetch和ES6(或多或少)似乎是一个更大的问题.我一直收到此错误消息:
无法加载Fetch API.对预检请求的响应未通过访问控制检查:请求的资源上不存在"Access-Control-Allow-Origin"标头.因此,不允许来源" http://127.0.0.1:3000 "访问.响应具有HTTP状态代码501.如果不透明响应满足您的需要,请将请求的模式设置为"no-cors"以获取禁用CORS的资源.
我知道这是因为我试图从我的localhost中获取该数据,解决方案应该使用CORS.现在我以为我确实这样做了,但不管怎么说它要么忽略我在标题中写的内容,要么问题是别的什么?
那么,是否存在实施问题?我做错了吗?遗憾的是我无法检查服务器日志.我真的有点卡在这里.
function performSignIn() {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');
headers.append('Access-Control-Allow-Origin', 'http://localhost:3000');
headers.append('Access-Control-Allow-Credentials', 'true');
headers.append('GET', 'POST', 'OPTIONS');
headers.append('Authorization', 'Basic ' + base64.encode(username + ":" + password));
fetch(sign_in, {
//mode: 'no-cors',
credentials: 'include',
method: 'POST',
headers: headers
})
.then(response => response.json())
.then(json => console.log(json))
.catch(error => console.log('Authorization failed : ' + error.message));
}
Run Code Online (Sandbox Code Playgroud)
我正在使用Chrome.我也尝试使用Chrome CORS插件,但后来我收到另一条错误消息:
当请求的凭据模式为"include"时,响应中"Access-Control-Allow-Origin"标头的值不能是通配符"*".因此,不允许来源" http://127.0.0.1:3000 "访问.XMLHttpRequest发起的请求的凭据模式由withCredentials属性控制.
我可以http://catfacts-api.appspot.com/api/facts?number=99通过Postman 点击这个终点并返回JSON
此外,我正在使用create-react-app,并希望避免设置任何服务器配置.
在我的客户端代码中我试图用fetch同样的东西,但我收到错误:
请求的资源上不存在"Access-Control-Allow-Origin"标头.因此不允许来源' http:// localhost:3000 '访问.如果不透明响应满足您的需求,请将请求的模式设置为"no-cors"以获取禁用CORS的资源.
所以我试图传入一个对象,我的Fetch将禁用CORS,如下所示:
fetch('http://catfacts-api.appspot.com/api/facts?number=99', { mode: 'no-cors'})
.then(blob => blob.json())
.then(data => {
console.table(data);
return data;
})
.catch(e => {
console.log(e);
return e;
});
Run Code Online (Sandbox Code Playgroud)
有趣的是,我得到的错误实际上是这个函数的语法错误.我不确定我的实际fetch是否已损坏,因为当我删除{mode:'no-cors'}对象,并为其提供不同的URL时,它可以正常工作.
我也尝试传入该对象{ mode: 'opaque'},但这会从上面返回原始错误.
我相信我需要做的就是禁用CORS ..我错过了什么?
我使用fetch()从api服务器获取数据.我的错误看起来像这样:
Uncaught (in promise) SyntaxError: Unexpected end of input at
fetch.then.blob.
Run Code Online (Sandbox Code Playgroud)
你能告诉我我做错了什么吗?
const weatherAPi ='https://www.metaweather.com/api/location/523920';
fetch(weatherAPi, {
mode: 'no-cors'
}).then(blob => blob.json())
.then(data => console.log(data))
Run Code Online (Sandbox Code Playgroud) 我正在尝试正确解释从 fetch 调用到 URL 的响应,我认为它是一个 json 字符串。我已经根据这里的类似帖子尝试了许多变体,但没有什么能让我使用有用的数据。这是一种尝试:
fetch('http://serverURL/api/ready/', {method: "POST", mode: "no-cors"})
.then(function(response) {
response.json().then(function(data) {
console.log('data:' + data);
});
})
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
Run Code Online (Sandbox Code Playgroud)
这会在控制台中返回一个语法错误:
SyntaxError: JSON.parse: JSON 数据第 1 行第 1 列的数据意外结束
所以也许它不是 JSON...如果我在 console.log 行上放置一个断点,并将鼠标悬停在响应(上面的行)上,我会看到带有各种字段的响应对象 (?):
不知道如何解释...status:0 表明它没有得到有效的响应。但是,如果我检查开发人员工具中的 Network 选项卡,然后单击 fetch 行,则状态为 200,并且响应窗口/JSON 部分会显示消息信息,如果您只是将 URL 放入浏览器 URL 中,您也会看到这些信息直接酒吧。与显示 JSON 字符串的“响应负载”部分一样:
{"msg": "API 已准备就绪。", "success": true}
所以......它看起来像json,不是吗?但是 fetch 无法将其作为 json 摄取?
这是另一种变体,但使用 response.text() 而不是 response.json()
fetch('http://serverURL/api/ready/', {method: "POST", mode: "no-cors"})
.then((response) => {
console.log(response);
response.text().then((data) …Run Code Online (Sandbox Code Playgroud) 我正在尝试从localhost访问Deezer API,但我一直收到以下错误:
Fetch API cannot load http://api.deezer.com/search/track/autocomplete?limit=1&q=eminem.
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost' is therefore not allowed access.
If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Run Code Online (Sandbox Code Playgroud)
localhost的响应标头确实有Access-Control-Allow-Origin标头(Access-Control-Allow-Origin:*).
我使用的是像获取:
fetch('http://api.deezer.com/search/track/autocomplete?limit=1&q=eminem').
我究竟做错了什么?
我一直在尝试创建一个 React 站点,它会从 API 获取 GET 响应并将其打印到我的 .html 文件中。我已经成功地正确获取了文件,但无法访问服务器发送给我的 JSON 数据。
如果我在 Fetch 请求中使用 no-cors,我会得到一个几乎不包含任何内容的不透明响应,但如果我转到开发人员工具,我可以在那里找到我的数据并读取它。如果我确实使用 cors,几乎同样的事情。我收到 403 错误,但我的数据位于浏览器内存中,但我的代码未将其打印出来。我可以在开发者工具中找到网络的回复。
为什么服务器给我一个错误,但我仍然得到我的数据?如果它在浏览器中,我该如何访问它?
class Clock extends React.Component {
constructor(props) {
super(props)
this.state = {data2: []}
this.apihaku = this.apihaku.bind(this)
}
componentDidMount() {
this.apihaku(),
console.log("Hei")
}
apihaku () {
fetch('https://#######/mapi/profile/',
{method: 'GET', mode:'no-cors', credentials: 'include',
headers: {Accept: 'application/json'}}
).then((response) => {
console.log(response);
response.json().then((data) =>{
console.log(data);
});
});
}
render() {
return <div>
<button>Button</button>
</div>
}}
ReactDOM.render(
<Clock />,
document.getElementById('content')
)
Run Code Online (Sandbox Code Playgroud)
编辑:尝试建议后出现错误图像
https://i.stack.imgur.com/wp693.png
我正在制作一个专门用于电子邮件订阅者的组件......就像这样
import React from "react";
class SubscribeOffer extends React.Component {
constructor () {
super();
this.state={
email: ""
}
}
fillEmailToSubscribe = (event) => {
this.setState({email: event.target.value});
}
submitEmailToSubscribe = () => {
if (this.state.email > 3) {
fetch('https://(myuser).list-manage.com/subscribe/post?u=(somenumber)&id=(myid)'
,{
mode: 'no-cors',
method:'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
email:this.state.email
})
})
.then(response => response.json())
.then(() => {
alert('Thank you for subscribing!');
})
}
}
render () {
return (
<div>
<h1>Get updated upcoming events in your inbox everyday!</h1>
<p>Would you like …Run Code Online (Sandbox Code Playgroud) 我正在尝试 从using模式中获取html位于 url 的文件,但响应被 CORB(跨源读取阻塞)阻止。https://sub.app.test/htmlhttps://app.testno-cors
fetch('https://sub.app.test/html', { mode: 'no-cors'})
Run Code Online (Sandbox Code Playgroud)
为什么?