如果angularjs托管在远程计算机上,Nodejs应用程序将无法与3000端口上的angular应用程序连接。
但是如果两个应用程序(nodejs和angular)都托管在一台计算机上,则可以连接。我缺少什么配置? 共享以下nodejs服务器应用程序代码。
var OrderServer = /** @class */ (function () {
function OrderServer() {
this._orderService = new order_service_1.OrderService();
this._pushNotificationSenderService = new push_notification_sender_service_1.PushNotificationSenderService();
this.createApp();
this.defineApiRoutes();
this.config();
this.createServer();
this.sockets();
this.listen();
}
OrderServer.prototype.getApp = function () {
return this.app;
};
OrderServer.prototype.createApp = function () {
this.app = express();
this.app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:8080");
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
this.app.use(express.json());
};
OrderServer.prototype.defineApiRoutes = function () {
this.app.route('/api/notifications')
.post(add_push_subscriber_1.addPushSubscriber);
};
OrderServer.prototype.config = function () {
this.port = process.env.PORT || OrderServer.PORT;
};
OrderServer.prototype.createServer = function () {
this.server = http_1.createServer(this.app);
};
OrderServer.prototype.sockets = function () {
this.io = socketIo(this.server);
};
OrderServer.prototype.listen = function () {
var _this = this;
this.server.listen(this.port, function () {
console.log('Running server on port %s', _this.port);
});
this.io.on('connect', function (socket) {
console.log('Connected client on port %s.', _this.port);
setInterval(function () {
_this._orderService.getNewNProcessingOrders(_this.io);
//this._pushNotificationSenderService.sendNotification();
}, 180000);
});
};
OrderServer.PORT = 3000;
return OrderServer;
}());
exports.OrderServer = OrderServer;
答案 0 :(得分:0)
在角度项目的根文件夹中创建一个proxy.conf.json
文件。
AngularCLI Documentation about proxies.
示例内容:
{
"proxy": {
"target": "https://localhost:3000/",
"secure": false,
"pathRewrite": {
"^proxy": ""
}
}
}
然后在角度应用angular/root/folder/environments/
的环境文件中为development
(environment.ts)和production
(environment.prod.ts)创建一个URL库,并在任何地方使用此前缀您要访问后端。
示例环境配置:
export const environment = {
production: false,
backendBaseKey: '/proxy/'
};
角度服务示例:
// Depending on dev/prod the according env is imported
import {environment} from "../../environments/environment";
[...]
fetch(){
return this.http.get(environment.backendBaseKey+'/my-endpoint');
}
然后在本地运行时通过
ng serve --proxy-config proxy.conf.json