Reputation: 347
When ever I fetch this google API its giving me this error message within the console log what am I doing wrong?
Failed to load resource: the server responded with a status of 404 () localhost/:1 Fetch API cannot load https://googleapis.com/books/v1/volumes?q=harry%20potter. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 404. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Code~
import React, { Component } from 'react';
import { FormGroup, FormControl, InputGroup, Glyphicon } from 'react-bootstrap';
class Global extends Component {
constructor(props) {
super(props);
this.state = {
query: ''
}
}
search() {
const BASE_URL = 'https://googleapis.com/books/v1/volumes?q='
fetch(`${BASE_URL}${this.state.query}`, {
method: 'GET',
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
})
.then(response => response.json())
.then(json => console.log(json));
}
render() {
return(
<div className="Global">
<h2> Book Explorer!</h2>
<FormGroup>
<InputGroup>
<FormControl
type="text"
placeholder="Search for a book"
onChange={event => this.setState({query: event.target.value})}
onKeyPress={event => {
if (event.key === 'Enter') {
this.search();
}
}}
/>
<InputGroup.Addon onClick={() => this.search()}>
<Glyphicon glyph="search"></Glyphicon>
</InputGroup.Addon>
</InputGroup>
</FormGroup>
</div>
)
}
}
export default Global;
Upvotes: 2
Views: 4663
Reputation: 2242
EDITED VERSION:
This is an issue with CORS, so you may consider setting more headers' params in the fetch
:
search() {
const BASE_URL = 'https://googleapis.com/books/v1/volumes?q='
fetch(`${BASE_URL}${this.state.query}`, {
method: 'GET',
headers:{
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials':true,
'Access-Control-Allow-Methods':'POST, GET'
}
})
.then(response => response.json())
.then(json => console.log(json));
}
=================
You forgot binding your search()
function into the component, so just add it into your constructor:
constructor(props) {
super(props);
this.state = {
query: ''
}
this.search = this.search.bind(this);
}
OR: Revising search()
to be auto-bound:
search = () => {
// copy your whole logics here
}
After that, ${BASE_URL}${this.state.query}
will return the correct value
Upvotes: 1