TypeError:无法在'Window'上执行'fetch':无效的值 [英] TypeError: Failed to execute 'fetch' on 'Window': Invalid value
问题描述
我尝试使用fetch从后端调用使用react,而不使用libs(例如Axios)。所以我创建了这个函数:
I've tried to use fetch to call from backend using react, without libs (such as Axios). So I created this function:
export function api(url, method, body, isHeaderContentType,isRequestHeaderAuthentication,header, succesHandler, errorHandler) {
const prefix = 'link';
console.log("url:",prefix+url);
const contentType = isHeaderContentType ? {
'Content-Type': 'application/json',
} : {};
const auth = isRequestHeaderAuthentication
? {
Authorization: `Bearer ${AuthUtils.getTokenUser}`,
}
: {};
fetch(prefix + url, {
method,
headers: {
...contentType,
...auth,
...header,
},
protocol:'http:',
body,
})
.then(response => {
response.json().then(json => {
if (response.ok) {
console.log("method", json);
if (succesHandler) {
succesHandler(json)
}
} else {
return Promise.reject(json)
}
})
})
.catch(err => {
console.log("error",`${url} ${err}`);
if (errorHandler) {
errorHandler(err);
}
})
}
并将其称为这样
} and call it like this
api(
`link`,
"GET",
null,
true,
true,
null,
response => {
this.setState({profile:response.data})
},
err => {
console.log('error', err);
}
);
我在这个函数中调用我的api():
i call my api() inside this function:
getProfileUser = () =>{
if (!isUserAuthenticated()){
history.push('/signin')
}else {
api(
`link`,
"GET",
null,
true,
true,
null,
response => {
this.setState({profile:response.data})
},
err => {
console.log('error', err);
}
);
}
};
这是我的完整组件:
export default class Profile extends Component {
constructor(props) {
super(props);
this.state = {
profile:[]
}
}
getProfileUser = () =>{
if (!isUserAuthenticated()){
someCode
}else {
api(
`link`,
"GET",
null,
true,
true,
null,
response => {
this.setState({profile:response.data})
},
err => {
console.log('error', err);
}
);
}
};
componentDidMount() {
this.getProfileUser();
}
render(){
return(
<div>
hello
</div>
)
}
}
但当我试图运行它时,我得到一个这样的错误
but when i tried to run it, i got an error like this
TypeError:无法在'Window'上执行'fetch':无效值
TypeError: Failed to execute 'fetch' on 'Window': Invalid value
有没有人知道我的代码有什么问题?当我使用POST方法时该功能有效,但当我使用GET方法时它不起作用
Is there anyone who knows what's wrong with my code? The function works when I use the "POST" method, but it doesn't work when I use "GET" method
推荐答案
当我尝试在我的fetch调用中添加授权
标头时,这也发生在我身上。在我的情况下,它是由标题字符串中的换行符引起的,即 Bearer:\ nsomelong-token
。更改为新线到空间解决了问题。
This also happened to me when I tried to add an Authorization
header to my fetch calls. In my case it was caused by a newline character in the header string, i.e. Bearer:\nsomelong-token
. Changing to the new line to a space solved the problem.
这篇关于TypeError:无法在'Window'上执行'fetch':无效的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!