NodeJS 从JSON数组中获取元素以显示为文本

fjaof16o  于 2022-12-12  发布在  Node.js
关注(0)|答案(2)|浏览(129)

所以我尝试从JSON对象中得到一个first_name,它有一个数组元素,通过迭代它,例如,如果我输入'罗恩',它将显示为文本,但由于某种原因,我不能显示为文本,除非我发送一个响应'

playerName: nbaPlayer[0]

但它只将一个元素显示为文本,因为其他元素不在响应中

在服务器中响应enter image description here
这里是一个代码获取,我使用搜索栏从车把搜索一个名字

const nbaForm = document.querySelector('form')
const search = document.querySelector('input')

const messageOne = document.querySelector('#player-1')

nbaForm.addEventListener('submit', (event) => {
    event.preventDefault()
    const playerSearch = search.value

    messageOne.textContent = 'Loading...'

    fetch('http://localhost:4000/nba').then((response) => {
        response.json().then(nbaData => {
       
            if (nbaData.playerName === playerSearch) {
                messageOne.textContent = nbaData.playerName
            } else {
                messageOne.textContent = 'not found'
            } 
        })
    })
})

请求方法

app.get('/nba', (req,res) => {
    networkManager.nbaPlayerData((data)=>{
        /
        var nbaPlayer = []
     
        for(var i=0; i<data.data.length; i++){
            nbaPlayer.push(data.data[i].first_name)
        }
        console.log(nbaPlayer)
        res.send({ 
            playerName: nbaPlayer
})
    })
})

车把档

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,  initial-scale=1.0">
    <title>NBA</title>
    <link rel = "stylesheet" href="/css/style.css"> 
    
</head>
<body>
     <div class="main-content">
        <h1>NBA SERVER</h1>
        <p>Use this site to get NBA player</p>

        <form action="">
            <input placeholder="Type a players name">
            <button>Search</button>
        </form>
        
        <p id="player-1"></p>
      
      <h1>{{playerName}}</h1>
    </div>

    
  
   <script src ="/js/fetch-app.js"></script>
</body>
</html>
wsewodh2

wsewodh21#

试试这个。

fetch('http://localhost:4000/nba').then((response) => {
        response.json().then(nbaData => {
       var index = nbaData.playerName.indexOf(playerSearch)
            if (index !== -1) {
                messageOne.textContent = nbaData.playerName[index]
            } else {
                messageOne.textContent = 'not found'
            } 
        })
    })
rryofs0p

rryofs0p2#

您正在从以下位置获取数组

res.send({ 
            playerName: nbaPlayer // nbaPlayer is array
})

但是在提取过程中,您希望从简单对象中获取数据,

相关问题