未找到React Fetch Google API 404

时间:2017-05-12 17:43:32

标签: reactjs google-api

尝试通过反应获取谷歌API,但我收到404错误。更多的背景是我正在构建一个Web应用程序,当我输入书名时,使用谷歌书api向我发回一个值。我不确定我做错了什么。我已经尝试了许多我正在做的课程,我们应该这样做,并且我的代码与教师相同。我认为它必须对本地主机3000的特权做一些事情?但我再次不确定。

继承我的代码

~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 :(得分:0)

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));
}

只需将headers键添加到选项