提问者:小点点

为什么Knex要在我的表数据库中插入空值?


我有一个通过express连接的SQLite数据库,并且有使用express路由连接前端和后端的控制器。

表数据库

  return knex.schema.createTable('stocks', (table)  => {
          table.string('ticker')
          table.date('date')
          table.integer('open')
          table.integer('close')
          table.integer('high')
          table.integer('last')
          table.integer('volume')
        })
        .then(() => {
         
          console.log('Table \'stocks\' created')
        })
        .catch((error) => {
          console.error(`There was an error creating table: ${error}`)
        })
      }
    })
    .then(() => {
      // Log success message
      console.log('Ayree')
    })
    .catch((error) => {
      console.error(`There was an error setting up the database: ${error}`)
    })

Knex插入行

exports.booksCreate = async (req, res) => {
  // Add new book to database
  knex('stocks')
    .insert({ // insert new record, a book
      "ticker": req.body.ticker,
      'date': req.body.date,
      'open': req.body.open,
      'close': req.body.close,
      'high': req.body.high,
      'last': req.body.last,
      'volume': req.body.volume,
    })
    .then(() => {
      // Send a success message in response
      res.json({ message: ` \'${req.body.ticker}\' added at ${req.body.date} created.` })
    })
    .catch(err => {
      // Send a error message in response
      res.json({ message: `There was an error creating ${req.body.ticker}  ${err}` })
    })
}

反应前端

// Create Bookshelf component
export const Bookshelf = () => {
  // Prepare states
   const [stock, setStock] = useState([])
   const [stockApi, setStockApi] = useState([])
  const [loading, setLoading] = useState(true)

  // Fetch all books on initial render
  useEffect(() => {
   
    getStockData();
    handleBookCreate();
  }, [])


  //StockData
const getStockData = ()  => { 
    axios
    .get("http://api.marketstack.com/v1/intraday/latest?access_key=72ad8c2f489983f30aaedd0181414b43&symbols=AAPL"       )
    .then( da => {
       setStock(da.data.data[0]) 
        console.log(da.data.data[0])
    } )
} 

// Create new book
  const handleBookCreate = () => {
    // Send POST request to 'books/create' endpoint
    axios
      .post('http://localhost:4001/books/create', { 
        ticker: stock.symbol,
        date: stock.date,
        open: stock.open,
        close: stock.close,
        high: stock.high,
        last: stock.last,
        volume: stock.volume,
      })
      .then(res => {
        console.log(res.data)

        // Fetch all books to refresh
        // the books on the bookshelf list
        fetchBooks()
      })
      .catch(error => console.error(`There was an error creating the ${stock} book: ${error}`))
  }

这里的问题是在前端,当我使用stock.symbol时,我得到的值为null,但当我用“text”替换stock.symbol,我得到的值为text。我在这里做错了什么?谢谢!

附注-这是常量存货

close: 115.08
date: "2020-10-09T00:00:00+0000"
exchange: "IEXG"
high: 116.4
last: 114.97
low: 114.5901
open: 116.25
symbol: "AAPL"
volume: 82322071
__proto__: Object

共1个答案

匿名用户

在读了一段时间关于HTTP调用和它们是如何执行的之后。这个解决方案对我有效。

 useEffect( () => {

const fetchData = async ( ) => { 

  const getit =  await getStockData(); setStock(getit); 
    handleBookCreate(getit); 
    } 
         fetchData();

  }, [])

基本上,在初始renderuseEffect上,使API调用getStockData(),并且await将使stocksetStock钩子的设置在承诺执行后起作用。只有这样,stock才会包含HandleBookCreate()向服务器路由器发送POST请求所需的数据,以执行在我的表数据库中插入记录的函数。