2

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;

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

9 Comments

So I added the this.search = this.search.bind(this); into the const identical to what you have posed but I am still getting this message. Failed to load resource: the server responded with a status of 404 (Not Found) 2bundle.js:37487 GET googleapis.com/books/v1/volumes?q=hi 404 ()
How about the API url, which returns it self an 404: googleapis.com/books/v1/volumes?q=harry%20potter I tried and it is not found !!
Hey Thinh in the original post that was what I had in my search bar. So just a better understanding is I am building an application that is based off the google books api. Where when you enter in a book name in the search bar it will return back some strings or values from the google API. The only reason why the harry potter says 404 not found is I am unsure if my const url or if I have something incorrect or what I did wrong.
I just added a fix for CORS above, would you mind trying that again, thanks
Tried the above but I still get the same message I am thinking maybe it has something to do with my permissions from local host 3000. I really don't know. I really appreciate the help though thinh.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.