gpt4 book ai didi

javascript - 类型错误 : Failed to execute 'fetch' on 'Window' : Invalid value

转载 作者:可可西里 更新时间:2023-11-01 01:42:27 25 4
gpt4 key购买 nike

我尝试使用 fetch 从后端使用 react 调用,没有库(例如 Axios)。所以我创建了这个函数:

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);
}
})

}并这样调用它

api(
`link`,
"GET",
null,
true,
true,
null,
response => {
this.setState({profile:response.data})
},
err => {
console.log('error', err);
}
);

我在这个函数中调用了我的 api():

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>
)
}

但是当我尝试运行它时,出现了这样的错误

TypeError: Failed to execute 'fetch' on 'Window': Invalid value

有谁知道我的代码有什么问题吗?当我使用“POST”方法时该功能有效,但当我使用“GET”方法时该功能无效

最佳答案

当我尝试将 Authorization header 添加到我的 fetch 调用时,这也发生在我身上。在我的例子中,它是由 header 字符串中的换行符引起的,即 Bearer:\nsomelong-token。将新行更改为空格解决了问题。

关于javascript - 类型错误 : Failed to execute 'fetch' on 'Window' : Invalid value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49109878/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com