React Fetch Google API

时间:2017-05-12 06:00:29

标签: reactjs google-api

我什么时候拿到这个谷歌API,它在控制台日志中给我这个错误信息我做错了什么?

无法加载资源:服务器响应状态为404() localhost /:1 Fetch API无法加载https://googleapis.com/books/v1/volumes?q=harry%20potter。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许原点“http://localhost:3000”访问。响应具有HTTP状态代码404.如果不透明响应满足您的需要,请将请求的模式设置为“no-cors”以获取禁用CORS的资源。

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 个答案:

答案 0 :(得分:1)

已编辑版本

这是CORS的一个问题,因此您可以考虑在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));
}

=================

您忘记将search()函数绑定到组件中,因此只需将其添加到构造函数中:

constructor(props) {
    super(props);
    this.state = {
        query: ''
    }
    this.search = this.search.bind(this);
}

:修改search()自动绑定:

search = () => {
  // copy your whole logics here
}

之后,${BASE_URL}${this.state.query}将返回正确的值