简体   繁体   中英

Unable to send data from node server to ajax

In my server file I am trying to send over data from a txt file and receive it in ajax like so

app.get('/send', function(req, res) {
showData = fs.readFile('file.txt', 'utf8', function(err, data) {
  res.send({data:data})
  })
})

It reaches my ajax code and I want to append it to my html but I am unable to

console.log(response.data)
            response.data.forEach(function(val) {
                console.log(val.id)
                tbodyEl.append('\
                    <tr>\
                        <th class="id">' + val.id + '</th>\
                    </tr>\
                    ')
            })

When I send through just a normal json variable from my server file it works but when I try use the text file it doesn't (saying TypeError: response.data.forEach is not a function )

There is a typo in the code you've included => response.dataata .

You also need to JSON.parse() the response data.

Assuming that the code you're running is typo-free and the response has been parsed, the other issue you could be facing is that the file contains invalid JSON or does not contain an Array.

If you want to keep forEach on the Ajax side, an alternative solution is to change res.send({data:data}) to res.send(data) . Assuming that data is an array, you can then parse on the Ajax side with JSON.parse(response).forEach(...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM