Reputation: 411
I deployed my angular 6 app to Heroku ( https://angulardictionary.herokuapp.com/).
But I'm getting the error SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse.
I understand what this error means: The response returns html instead of JSON. My question is: how can I fix it?
I tried:
res.send(object)
res.json(object)
Here's my code:
server.js
app.get('*', function(req,res) {
res.sendFile(path.join(__dirname +'/dist/frontend/index.html'));
});
app.get('/api/words', function(req, res){
fs.readFile('newWords.xml', 'utf-8', function (err, data){
if(err){
console.log('error');
//res.send(err);
} else{
parser.parseString(data, function (err, result) {
let words = result['entry']['form'];
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(words));
web.service.ts:
getWords(name: string, option: any):Observable<Word[]>{
return this.http.get<Word[]>('/api/words',{
params: {
name:name,
option:option
}
}
);
}
and I call this function in: home.component.ts:
getWordList(){
this.webservice.getWords(this.spelling, this.selected)
.subscribe((res: Array<Word>)=> {
this.elements = res.filter(d=> d.orth == this.spelling || d.asuddimIsem
== this.spelling);
}
}
It seems as if all the http calls go directly to the default route (app.get('*', function(req,res)), skipping (app.get('/api/words')).
Upvotes: 1
Views: 7398
Reputation: 5311
It seems as if all the http calls go directly to the default route (app.get('*', function(req,res))
, skipping (app.get('/api/words'))
this is correct. The order in which routes are defined matters. You have to put the wildcard *
route at last. As for the other API, you may not need to stringify JSON.stringify()
the response, you can simply do res.send(words)
.
Upvotes: 3