在 Heroku 前端部署 Angular/Express 应用程序时遇到问题,无法到达 API 端点



目前正在开发中,它工作得很好... 前端localhost:4200,后端localhost:8080

但是,我只是部署了它并显示前端,但没有从 API 获取数据,因为在我的app.service.ts中我正在执行以下操作:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class ApiService {
private apiUrl = 'http://localhost:8080/api'
constructor(private http: HttpClient) { }
public getNews() {
return this.http.get(`${this.apiUrl}/countries`)
}
}

如您所见,我正在对localhost:8080进行硬编码,并且在开发中运行良好,但是在生产方面,Heroku 没有为我分配port 8080,它为我分配了另一个。

话虽如此...我如何调整它以阅读 Heroku 给我的端口?

这是我的应用程序.js文件

const express = require('express');
const app = express();
const scrapper = require('./backend/scrapper')
// Create link to Angular build directory
var distDir = __dirname + "/dist/covid19";
app.use(express.static(distDir));
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.use("/api/countries", async (req, res, next) => {
const data = await scrapper.getCountries()
res.status(200).json(data)
})
const port = process.env.PORT || 8080;
app.listen(port, () => {
console.log(`API listening on port ${port}...`);
});
module.exports = app;

如您所见,我声明我的端口是process.env.PORT || 8080,但这是为后端...如何在service.ts文件中的 API 调用中实现这一点?

你们为我指出了正确的方向,但准确地说:

我注意到在 Angular 中,您会得到一个包含两个文件 1 的environments文件夹。environment.tsenvironment.prod.ts.

我只需要确保在部署yourappname.herokuapp.com后使用 Heroku 为我的应用程序提供的 URL,方法是在我的environments.prod.ts中执行以下操作(这是 Heroku 将要寻找的那个)

export const environment = {
production: true,
apiUrl: "https://yourappname.herokuapp.com/api"
};

在我的api.service.ts中,我最终得到了以下代码:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from '../environments/environment'
const API_URL = environment.apiUrl;
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(private http: HttpClient) { }
public getNews() {
return this.http.get(API_URL + '/countries')
}
}

当您在 Heroku 上部署 Web 服务器时,您会绑定到 Heroku 告诉您绑定到的$PORT

访问已部署的应用时,无需指定端口。您只需连接到yourappname.heroku.com.DNS 会自动将其转换为ipaddress:port

所以在你的前端,你只是指向yourappname.heroku.com而不是ipaddress:port

部署应用时,必须参考生产变量。我喜欢使用"@angular/核心"包中包含的isDevMode函数。

import { isDevMode } from '@angular/core';
setUrl(){
if(isDevMode() == true){
//in development mode
api_url = "localhost:4200"
}else{
api_url = "heroku.app_url.app"
}
}

此函数可让你知道应用在哪种模式下运行,以便你可以使用它在连接字符串之间切换。

最新更新