So i am trying to get a first_name from JSON object which has array of elements by iterating through it, for example if i type 'Ron' it will display as a text but for some reason I can't get display it as a text unless i send in a respond this `
playerName: nbaPlayer[0]
But it only displays one element as a text since others are not in a response
reponse in a server enter image description here
Here is a code for fetch where i use search bar from handlebars to search for a first_name
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'
}
})
})
})
request method
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
})
})
})
handlebars file
<!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 >
<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>
CodePudding user response:
try this.
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'
}
})
})
CodePudding user response:
You are getting an array from
res.send({
playerName: nbaPlayer // nbaPlayer is array
})
but in your fetch, you want to get data as from simple object