我在单击按钮时调用此函数。 我在 API 中添加了一个标头,但它仍然显示错误。
让 getData = () => { console.log("getData 函数已启动");
const options = {
method: "GET",
headers: new Headers({ 'content-type': 'application/json' }),
mode: 'no-cors'
};
fetch("http://167.71.226.242/", options).then((response) => {
console.log("Inside 1st then");
return response.json();
}).then((data) => {
console.log("Inside 2nd then");
console.log(data);
});
}
答案 0 :(得分:0)
您可能只想执行此操作并使用正确的标题名称,因为您的标题名称是小写的:
fetch('/', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
}).then(...);
看起来您也不需要使用 new Headers();
。
您可能也不需要mode: 'no-cors'
,但这是您的要求:)
答案 1 :(得分:0)
var requestOptions = {
'content-type': 'application/json',
method: 'GET',
redirect: 'follow'
};
fetch("http://167.71.226.242", requestOptions)
.then(response => response.json())
.then(data => console.log(data));
此代码有效。您不在选项中使用 new Header(...) ! 阅读有关 fetch() 的更多信息 https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#supplying_request_options