如何从服务器获取(或返回)数据?

时间:2018-12-15 18:19:54

标签: javascript reactjs fetch

我尝试通过带有react的url来获取数据。服务器提供json(String jsonBooks = new Gson().toJson(books);中的String中的对象列表的url。我试图在react app和render中得到这个。但这是错误的: TypeError:无法读取未定义的属性“地图”

import React, { Component } from 'react';
import './App.css';

class App extends Component {

        state = {
            books: []
        }

        componentDidMount() {
            fetch(`http://localhost:8080/app/bookshop/books`,
                {'mode': 'no-cors'},
                {
                headers: {
                    'Access-Control-Allow-Origin': '*',
                    'Access-Control-Allow-Methods': 'GET, POST, HEAD, OPTIONS, PUT, DELETE, PATCH',
                    'Access-Control-Allow-Headers': 'X-Requested-With,content-type',
                    'Access-Control-Allow-Credentials': true
                }})
                .then(res => {
                    const books = res.data;
                    // console.log(res.data);
                    this.setState({books});
                });
        }

    // http://localhost:8080/app/bookshop/books
cd
      render() {
          return (

              <div>
                  <h1>Books:</h1>
                  <table>
                      <tr>
                          <th>Name</th>
                          <th>Author</th>
                          <th>Izdat</th>
                          <th>Genre</th>
                          <th>Price</th>
                          <th>Amount</th>
                      </tr>
                      {this.state.books.map(book =>
                          <tr><th>{book.name}</th>
                              <th>{book.author}</th>
                              <th>{book.izdat}</th>
                              <th>{book.genre}</th>
                              <th>{book.price}</th>
                              <th>{book.amount}</th>
                          </tr>
                      )}
                  </table>
              </div>
          );
      }
}
export default App;

这是在服务器上运行的功能(java,jax-rs):

@GET
@Produces({MediaType.APPLICATION_JSON})
@Path("/books")
public String Books() {
    BooksDao booksDao = new BooksDao();
    ArrayList<Book> books = booksDao.getBooks();
    String jsonBooks = new Gson().toJson(books);
    return jsonBooks;
}

我该怎么做?

2 个答案:

答案 0 :(得分:0)

您的渲染正在fetch承诺解决之前进行。您可以在调用state之前,将isLoading的字段添加到true并将其设置为fetch。就是true时,显示一个加载图标,然后在获取返回数据后,将isLoading设置为false并呈现书籍。

答案 1 :(得分:0)

对于正面抓取,应该为(无cors标头):

 componentDidMount() {
        fetch(`http://localhost:8080/app/bookshop/books`)
            .then(res => res.json())
            .then(books => this.setState({ books }))
            .catch(console.error)
    } 

在服务器上配置了cors标头,在这种情况下,我这样做了:

@GET
@Produces({MediaType.APPLICATION_JSON})
@Path("/books")
public Response Books() {
    BooksDao booksDao = new BooksDao();
    ArrayList<Book> books = booksDao.getBooks();
    String jsonBooks = new Gson().toJson(books);
    return Response
            .status(200)
            .header("Access-Control-Allow-Origin", "*")
            .header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization")
            .header("Access-Control-Allow-Credentials", "true")
            .header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
            .header("Access-Control-Max-Age", "1209600")
            .entity(jsonBooks)
            .build();
}