无法将数据从节点服务器发送到ajax

在我的服务器文件中,我试图从一个txt文件发送数据,然后像ajax那样接收它

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

它到达我的ajax代码,我想附加到我的HTML,但我无法

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

当我通过一个普通的jsonvariables从我的服务器文件发送它的作品,但是当我尝试使用文本文件它不(说TypeError:response.data.forEach不是一个函数)

在你所包含的代码中有一个input错误=> response.dataata

您还需要JSON.parse()响应数据。

假设你正在运行的代码没有打字错误,并且响应已被parsing,那么你可能面临的另一个问题是该文件包含无效的JSON或不包含数组。

如果你想在Ajax方面保持forEach,另一种解决scheme是将res.send({data:data})改为res.send(data) 。 假设数据是一个数组,您可以使用JSON.parse(response).forEach(...)来parsingAjax端JSON.parse(response).forEach(...)