I'm using angular 2. I have one component on front-end that calls with HttpClient get my function on back-end. My code on localhost works fine running "node server.js" and "ng serve", but when i put it on firebase (with "ng build --prod" and "firebase deploy") it gives me that error when load the page:
{
error: SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttpRequest.l
headers: t {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure during parsing for https://my-project-name.firebaseapp.com/test"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
}
I have tried to force the responseType as suggested in that answer Angular HttpClient "Http failure during parsing" but it gives me a compile error that the response is json and not text.
thats my code that works on localhost:
//file .ts
import { HttpClient } from '@angular/common/http';
...
...
constructor(private http: HttpClient){}
ngOnInit() {
this.http.get<{}>('http://localhost:8080/test').subscribe(res => {
console.log(res);
});
...
...
//file server.js
//Install express server
const express = require('express');
const path = require('path');
const app = express();
// Serve only the static files form the dist directory
app.use(express.static(__dirname + 'localhost:4200'));
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept, Authorization'
);
res.setHeader(
'Access-Control-Allow-Methods',
'GET, POST, PATCH, PUT, DELETE, OPTIONS'
);
next();
});
app.route('/test').get((req, res) => {
res.send({
cats: [{
name: 'lilly'
}, {
name: 'lucy'
}],
})
});
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname + 'localhost:4200'));
});
app.listen(process.env.PORT || 8080, () => {
console.log('online');
});
thats my code that doesn't work on firebase
//file .ts
import { HttpClient } from '@angular/common/http';
...
...
constructor(private http: HttpClient){}
ngOnInit() {
this.http
.get<{}>('https://my-project-name.firebaseapp.com/test')
.subscribe(res => {
console.log(res);
});
...
...
//server.js
//Install express server
const express = require('express');
const path = require('path');
const app = express();
// Serve only the static files form the dist directory
app.use(express.static(__dirname + '/dist/browser'));
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept, Authorization'
);
res.setHeader(
'Access-Control-Allow-Methods',
'GET, POST, PATCH, PUT, DELETE, OPTIONS'
);
next();
});
app.route('/test').get((req, res) => {
res.send({
cats: [{
name: 'lilly'
}, {
name: 'lucy'
}],
})
})
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname + '/dist/browser/index.html'));
});
app.listen(process.env.PORT || 8080);