TypeError:无法在'Window'上执行'fetch':无效的值

Rai*_*gan 16 javascript fetch reactjs

我尝试使用fetch从后端调用使用react,而不使用libs(例如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);
        }
    })
Run Code Online (Sandbox Code Playgroud)

并像这样称呼它

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

我在这个函数中调用我的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);
            }
        );
    }
};
Run Code Online (Sandbox Code Playgroud)

这是我的全部内容:

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>
    )
}
Run Code Online (Sandbox Code Playgroud)

}

但是当我试图运行它时,我得到了这样的错误

TypeError:无法在'Window'上执行'fetch':无效的值

有没有人知道我的代码有什么问题?该函数在我使用"POST"方法时有效,但在使用"GET"方法时它不起作用

Bob*_*les 13

对我来说,我在标题对象的中有一个无效字符。我不小心包含了“:”,这会引发所描述的错误。在 chrome 控制台中很难直观地看到。希望它可以帮助某人。

{ 'Authorization:':'Bearer etc...' }
Run Code Online (Sandbox Code Playgroud)


tfw*_*ght 8

当我尝试Authorization在我的fetch调用中添加标头时,这也发生在我身上.在我的情况下,它是由标题字符串中的换行符引起的,即Bearer:\nsomelong-token.更改到新线到空间解决了问题.

  • 发生在我身上,因为我有另一个角色(你不容易看到的角色)。很好的提示。 (2认同)

小智 7

我在将带有换行符的字符串传递到标头对象时遇到了这个问题,例如:

const myString = 'this is a string \nand this is a new line';
headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${token}`,
    'subscriptionId': myString
}
Run Code Online (Sandbox Code Playgroud)


小智 5

嘿,当我尝试使用 React 中的 fetch 方法加载数据时,我遇到了同样的问题。

const response = await fetch('/graphql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    query
  })
});
Run Code Online (Sandbox Code Playgroud)

我的内容类型中有一个额外的空格导致了错误,所以请查找相同的空格。