TypeError: no se pudo ejecutar 'fetch' en 'Window': valor no válido
Intenté usar fetch para llamar desde el backend usando react, sin libs (como Axios). Entonces creé esta función:
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);
}
})
} y llámalo así
api(
`link`,
"GET",
null,
true,
true,
null,
response => {
this.setState({profile:response.data})
},
err => {
console.log('error', err);
}
);
Llamo a mi api () dentro de esta función:
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);
}
);
}
};
Este es mi componente completo:
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>
)
}
}
pero cuando intenté ejecutarlo, recibí un error como este
TypeError: no se pudo ejecutar 'fetch' en 'Window': valor no válido
¿Hay alguien que sepa lo que está mal con mi código? La función funciona cuando uso el método "POST", pero no funciona cuando uso el método "GET"