Javascript 类型错误:无法在“窗口”上执行“获取”:值无效
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49109878/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeError: Failed to execute 'fetch' on 'Window': Invalid value
提问by Raihan Parlaungan
I've tried to use fetch to call from backend using react, without libs (such as Axios). So I created this function:
我尝试使用 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);
}
})
} and call it like this
并像这样称呼它
api(
`link`,
"GET",
null,
true,
true,
null,
response => {
this.setState({profile:response.data})
},
err => {
console.log('error', err);
}
);
i call my api() inside this function:
我在这个函数中调用了我的 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);
}
);
}
};
this is my full component:
这是我的完整组件:
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: Failed to execute 'fetch' on 'Window': Invalid value
类型错误:无法在“窗口”上执行“获取”:值无效
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
有没有人知道我的代码有什么问题?该函数在我使用“POST”方法时有效,但当我使用“GET”方法时它不起作用
回答by tfwright
This also happened to me when I tried to add an Authorizationheader to my fetch calls. In my case it was caused by a newline character in the header string, i.e. Bearer:\nsomelong-token. Changing the new line to a space solved the problem.
当我尝试Authorization向我的 fetch 调用添加标头时,这也发生在我身上。在我的情况下,它是由标题字符串中的换行符引起的,即Bearer:\nsomelong-token. 将新行更改为空格解决了问题。
回答by Ben Edge
I had this when passing a string with a newline character into the header object for example:
我在将带有换行符的字符串传递到标头对象时遇到了这个问题,例如:
const myString = 'this is a string \nand this is a new line';
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
'subscriptionId': myString
}
回答by BobbyTables
For me, i had an invalid character in a keyof the header object. I accidentally included the ":" and this throws the error described. Really difficult to visually see in the chrome console. Hope it helps someone.
对我来说,我在标题对象的键中有一个无效字符。我不小心包含了“:”,这会引发所描述的错误。在 chrome 控制台中很难直观地看到。希望它可以帮助某人。
{ 'Authorization:':'Bearer etc...' }
回答by Mariel Quezada
I got the same problem, but working with Angular 7, I was using a Interceptor service like this:
我遇到了同样的问题,但是在使用 Angular 7 时,我使用了这样的拦截器服务:
// headerservice.ts
public intercept() {
const token = Cookies.get('token');
this.Language = Cookies.get('language');
this.headers = new HttpHeaders(
{
Authorization: 'JWT ' + token,
'Accept-Language': this.Language
}
);
return this.headers;
}
//other file
this.headers = this.headersService.intercept();
But it doesn′t work on the other file where i am doing the fetch, so i remove the service and put the headers directly inside the function and it works! like this:
但是它不适用于我正在执行提取的另一个文件,所以我删除了该服务并将标题直接放在函数中并且它可以工作!像这样:
const token = Cookies.get('token');
const language = Cookies.get('language');
const headers = {
Authorization: 'JWT ' + token,
'Accept-Language': language
}
const fetchParams = { method: 'GET',
headers: (headers) };
fetch(url, fetchParams)
回答by Raihan Parlaungan
i've solve this problem with adding my frontend url to whitelist cors of my backend code
我已经通过将我的前端 url 添加到我的后端代码的白名单 cors 解决了这个问题
回答by Eugenijus S.
This error happened to me as well, however with different circumstances. I would like to share it in case someone else has this issue.
这个错误也发生在我身上,但是情况不同。我想分享它,以防其他人有这个问题。
So I got the error "TypeError: Failed to execute 'fetch' on 'Window': Invalid value" when I tried to upload a file with HTTP POST without using FormData. To solve the issue I used FormData object and appended properties and file itself:
因此,当我尝试在不使用 FormData 的情况下使用 HTTP POST 上传文件时,出现错误“ TypeError: Failed to execute 'fetch' on 'Window': Invalid value”。为了解决这个问题,我使用了 FormData 对象并附加了属性和文件本身:
let formData = new FormData();
formData.append('name', fileName);
formData.append('data', file);
then I used fetch to send the file with POST method. Here is pseudo code:
然后我使用 fetch 用 POST 方法发送文件。这是伪代码:
const options = {method: 'POST', formData};
fetch('http://www.someURL.com/upload', options);

