我正在使用angular2。我在前端有一个组件,可以通过HttpClient调用在后端获得我的功能。我在localhost上的代码在运行“ node server.js”和“ ng serve”时工作正常,但是当我将其放在firebase上(使用“ ng build --prod”和“ firebase deploy”)时,在加载页面时会给我该错误:
{
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"
}
我试图按照答案Angular HttpClient "Http failure during parsing"中的建议强制使用responseType,但是它给了我一个编译错误,该响应是json而不是文本。
多数民众赞成在我的代码可以在本地主机上工作:
//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');
});
那是我的代码在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);
答案 0 :(得分:0)
显然,firebase不支持我的代码模式(表示服务器端)。 我部署在heroku上(并且更改了代码上的链接),它可以工作。谢谢你的帮助。 如果有人发现如何在免费的Firebase计划中使用该模式,请随时向我提出建议。