Read the file from node and send it to the client as json. If the file exists, it works normally, but if the file cannot be read, an error is generated. What is causing the problem and how can I fix it?
res.json([{
result:resData
}]);
Of course you can do this.
res.json(resData);
However, in this case, the client JavaScript code needs to check the object before reading it. I think this is an unnecessary expense.
What I have tried:
Ajax
const jsonData = {'pID': id, lang: language };
$.getJSON(url, jsonData, function(result){
page = new pageData();
page.data = result[0].result;
let text = result[0].content;
let( text !== '' || text !== undefined ){
text = JSON.parse( text );
subtext = text.subscribe;
}
});
Node.js
let prevInstance = {};
app.get('/server', function(req, res){
let num = req.query.pID;
let resData = {};
resData = prevInstance[num].getData(num++);
let json_dir = '/local/jst.json';
if(fs.existsSync(json_dir){
let data = fs.readFile(json_dir, 'utf8', (err, data)=>{
res.json({
content:data,
result:resData,
}]);
});
}else{
res.json([{
result:resData
}]);
}
});
VM19127:1 Uncaught SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)