angular cli

by Moshe Vilner

通过Moshe Vilner

使用Angular CLI连接到服务器的最佳方法 (The best ways to connect to the server using Angular CLI)

Everybody who has used Angular CLI knows that it is a powerful tool which can take a front-end development job to a completely different level. It has all the common tasks like live reload, typescript transpiling, minification, and more. And it’s all preconfigured and ready to use with one simple command:

每个使用过Angular CLI的人都知道,它是一个功能强大的工具,可以将前端开发工作带到一个完全不同的水平。 它具有所有常见任务,例如实时重新加载,打字稿转换,缩小等。 所有这些都已预先配置,可以通过一个简单的命令使用:

ng build, ng serve, ng test.

But there is one (and a very important one) task that needs to be configured once the application is ready to start showing some data from the server…

但是一旦应用程序准备开始显示来自服务器的某些数据,就需要配置一项(也是非常重要的一项)任务……

Yes, no matter how great the Angular framework is, and how quickly and performant its components — at the end the purpose of SPA (single page application) is to interact with the server through HTTP requests.

是的,无论Angular框架有多强大,其组件有多快和性能如何— SPA的最终目的(单页应用程序)都是通过HTTP请求与服务器进行交互。

And here is the first obstacle that appears before every Angular CLI newbie: the Angular project runs on its own server (which runs by default at http://localhost:4200). Therefore, the requests to the API server are cross-domain, and, as you might know, the security of the web browser disallows the making of cross domain requests.

这是每个Angular CLI新手出现之前的第一个障碍:Angular项目在其自己的服务器上运行(默认情况下在http:// localhost:4200上运行 )。 因此,对API服务器的请求是跨域的 ,并且您可能知道,Web浏览器的安全性不允许进行跨域请求。

方法1:代理 (Approach 1: proxy)

Of course, the people at Angular CLI foresaw this issue and even built a special option for running an Angular project using a proxy configuration:

当然,Angular CLI的人预见到了这个问题,甚至为使用代理配置运行Angular项目构建了一个特殊选项:

ng serve  —-proxy-config proxy.conf.json

What is a proxy, you might ask? Well, browsers don’t allow you to make cross domain requests, but servers do. Using the proxy option means that you’re telling Angular CLI’s server to handle the request sent from Angular and resend it from the development server. This way, the one who “talks” with the API’s server is Angular CLI’s server.

您可能会问什么是代理? 好吧,浏览器不允许您发出跨域请求,但是服务器允许。 使用proxy选项意味着您要告诉Angular CLI的服务器处理从Angular发送的请求,然后从开发服务器重新发送该请求。 这样,与API的服务器“对话”的就是Angular CLI的服务器。

The proxy configuration requires the proxy.conf.json file to be added to the project. This is a JSON file with some basic settings. Here is an example of the contents of proxy.conf:

代理配置需要proxy.conf.json 文件添加到项目中。 这是具有一些基本设置的JSON文件。 这是proxy.conf内容的示例

{  "/api/*": {    "target": "http://localhost:3000",    "secure": false,    "pathRewrite": {"^/api" : ""}  }}

This code means that all requests that start with api/ will be resent to http://localhost:3000 (which is the API server’s address)

此代码意味着所有以api /开头的请求都将重新发送到http:// localhost:3000 (这是API服务器的地址)

方法2:CORS (Approach 2: CORS)

Browser security doesn’t allow you to make cross domain requests unless the Control-Allow-Origin header exists at the server’s response. Once you configured your API server to ‘‘answer’’ with this header, you can fetch and post data from a different domain.

浏览器安全性不允许您发出跨域请求,除非服务器响应中存在Control-Allow-Origin标头。 将API服务器配置为使用此标头“回答”后,您就可以从其他域中获取和发布数据。

This technique is called Cross Origin Resource Sharing, or CORS. Most of the common servers and server frameworks like Node.js’ Express, or Java Spring Boot can be easily configured to make CORS available.

此技术称为跨源资源共享或CORS。 大多数常见的服务器和服务器框架(如Node.js的Express或Java Spring Boot)都可以轻松配置为使CORS可用。

Here is some example code which sets the Node.js Express server to use CORS:

以下是一些示例代码,这些代码将Node.js Express服务器设置为使用CORS:

const cors = require('cors'); //<-- required installing 'cors' (npm i cors --save)const express = require('express');const app = express();app.use(cors()); //<-- That`s it, no more code needed!

Note that when using CORS, before each of the HTTP requests are sent, it will follow after the OPTIONS request (at the same URL) that checks to see if the CORS protocol is understood. This “double request” may affect your performance.

请注意,在使用CORS时,在发送每个HTTP请求之前,它将在OPTIONS请求(位于相同URL)之后进行,以检查是否理解CORS协议。 这个“双重要求”可能会影响您的表现。

生产方式 (Production Approach)

Ok, your Angular project is “talking” smoothly with server, getting and sending data in the developer environment. But the time of deployment has finally come, and you need your beautiful and preformant Angular app to be hosted somewhere (far away from Papa Angular CLI). So again you face the same problem: how to make it to connect to server.

好的,您的Angular项目正在与服务器“畅通”,在开发人员环境中获取和发送数据。 但是部署的时间终于到了,您需要将漂亮且性能卓越的Angular应用托管在某个地方(远离Papa Angular CLI)。 因此,您再次面临相同的问题:如何使其连接到服务器。

Only now there is a big difference: in the production environment (after running ng build command), the Angular app is no more than a bunch of HTML and JavaScript files.

只是现在有很大的不同:在生产环境中(运行ng build命令后),Angular应用仅是一堆HTML和JavaScript文件。

Actually the decision on how to host the application on the production server is an architectural decision, and architecture is far beyond the scope of this article. But there is one option I recommend that you consider.

实际上,关于如何在生产服务器上托管应用程序的决定是一项体系结构决定,而体系结构远远超出了本文的范围。 但是,我建议您考虑一种选择。

从API的服务器提供静态文件 (Serve Static Files From the API’s Server)

Yes, you can host your Angular project (once it has only HTML and JavaScript files) on the same server where data (APIs) is served from.

是的,您可以在提供数据(API)的同一服务器上托管Angular项目(一旦它只有HTML和JavaScript文件)。

One of the advantages of this strategy is that now you do not face any “cross-domain” issues, since the client and API are actually on the same server!

该策略的优点之一是,由于客户端和API实际上位于同一台服务器上,因此您现在无需面对任何“跨域”问题!

Of course, this approach requires the API’s server to be configured properly.

当然,此方法要求正确配置API的服务器。

Here is the code that exposes the “public” directory where Angular files can be hosted when using the Node Express server:

以下代码显示了使用Node Express服务器时可以在其中托管Angular文件的“公共”目录:

app.use(express.static('public'));  //<-- public directory that contains all angular files

Note that in this case, the way your app accesses the API in the development environment will be different from the way the API accessed it at production. Thus you may need to use different HTTP URLs in different environments (Like api/users/1 at dev and users/1 at production). You can use Angular CLI’s environment option to achieve this:

请注意,在这种情况下,您的应用程序在开发环境中访问API的方式将不同于生产环境中API访问它的方式。 因此,您可能需要在不同的环境中使用不同的HTTP URL(例如在dev处为api / users / 1 ,在生产环境中为users / 1 )。 您可以使用Angular CLI的环境选项来实现此目的:

// users.service.ts
const URL = 'users';return this.http.get(`${environment.baseUrl}/${URL}`);...
// example of environment.ts file:export const environment = {  production: false,  baseUrl: 'api',//<-- 'API/' prefix needed for proxy configuration };
// example of environment.prod.ts file:export const environment = {  production: true,  baseUrl: '', //<-- no 'API/' prefix needed};

结论 (Conclusion)

Angular CLI is without doubt a very powerful and robust tool . It makes our lives as front end developers easier in many ways. But it also requires you to make an architectural decision about the connection to the API’s server. Therefore, you need a clear understanding of the various ways client-server communication may be established.

毫无疑问,Angular CLI是一种非常强大的工具。 它使我们作为前端开发人员的生活在许多方面变得更加轻松。 但这还需要您做出与API服务器的连接的体系结构决策。 因此,您需要清楚地了解可以建立客户端-服务器通信的各种方式。

This article lists two approaches of handling this issue in the developer environment and also one recommendation about production architecture.Try to play with various compilations and see which one feels more convenient for you and your team.

本文列出了在开发人员环境中处理此问题的两种方法,以及有关生产体系结构的一种建议。尝试使用各种编译,看看哪种对您和您的团队更方便。

Have fun and let me know how it goes!

玩得开心,让我知道如何发展!

翻译自: https://www.freecodecamp.org/news/the-best-ways-to-connect-to-the-server-using-angular-cli-b0c6b699716c/

angular cli

angular cli_使用Angular CLI连接到服务器的最佳方法相关推荐

  1. 炉石一直显示连接服务器,炉石传说无法连接战网服务器怎么办 处理方法详解...

    很多玩炉石传说的小伙伴会遇到无法连接战网服务器这个问题,也是很头疼不会解决,今天菜灰就来告诉大家炉石传说无法连接战网服务器的解决方法,希望能够帮助到大家. 炉石传说无法连接请检查网络连接处理方法 这两 ...

  2. ecmall php传变量,PHP_ECMall支持SSL连接邮件服务器的配置方法详解,首先,主要是ecmall使用的phpmail - phpStudy...

    ECMall支持SSL连接邮件服务器的配置方法详解 首先,主要是ecmall使用的phpmailer版本太低,不支持加密连接. 然后,得对相应代码做一定调整. 1. 覆盖phpmailer 请从附件进 ...

  3. 或者指定的打印机没有连接到服务器上,“操作无法完成键入的打印机名不正确或者指定的打印机没有连接到服务器上”解决方法.doc...

    "操作无法完成键入的打印机名不正确或者指定的打印机没有连接到服务器上"解决方法.doc (2页) 本资源提供全文预览,点击全文预览即可全文预览,如果喜欢文档就下载吧,查找使用更方便 ...

  4. 阿里云国际版无法远程连接Windows服务器的解决方法

    免责声明:本文档可能包含第三方产品信息,该信息仅供参考.阿里云对第三方产品的性能.可靠性以及操作可能带来的潜在影响,不做任何暗示或其他形式的承诺. 概述 下面来和87cloud一起了解阿里云国际版无法 ...

  5. Adobe Creative Cloud for mac无法连接至服务器的解决方法

    有些时候我们发现Creative Cloud无法连接至服务器,其他网站可以打开,但想要想要登录adobe(登录需要用adobe账号)就404,也许是由于修改了host造成的.一起来跟小编看看解决方法吧 ...

  6. win无法连接网络计算机6,Win7玩英雄联盟提示无法连接到服务器六种解决方法

    说到LOL英雄联盟相信很多玩家都比较熟悉了,它是一款网络游戏.但是最近有用户说Win7系统玩英雄联盟的时候提示"连接失败:无法连接到服务器,请检查您的网络连接"(如下图所示),导致 ...

  7. ecmall mysql.php_ECMall支持SSL连接邮件服务器的配置方法详解

    首先,主要是ecmall使用的phpmailer版本太低,不支持加密连接. 然后,得对相应代码做一定调整. 1. 覆盖phpmailer 请从附件进行下载: 2. 改造lib 涉及到两个lib:mai ...

  8. qq炫舞手游显示无法连接服务器失败,QQ炫舞手游无法连接版本服务器失败解决方法...

    QQ炫舞手游3月21日无法连接服务器解决方法,今天游戏出现了登陆问题,让很多的玩家都非常的郁闷,那么QQ炫舞手游无法连接服务器如何解决呢?相信很多玩家还不是很清楚,下面小编就带来相关攻略,小伙伴们千万 ...

  9. SolidWorks2019打开后显示“无法连接到服务器”的解决方法

    SolidWorks2019打开后显示下图的解决方法 1.打开安装包,将SolidWorks_Server文件夹中的所有文件复制到某一目录下,例如:C:\SolidWorks2019\SolidWor ...

最新文章

  1. SpringBoot微服务 b2b2c 多用户商城系统(八)springboot整合mongodb
  2. 成功解决python\ops\seq2seq.py TypeError: ms_error() got an unexpected keyword argument 'logits'
  3. [leetcode] 103.二叉树的锯齿形遍历
  4. C++学习——static
  5. 伪指令endp告诉汇编程序_第2章 指令系统及汇编语言程序设计 题库和答案
  6. window.showModalDialog模式窗口无法在子窗口访问解决办法
  7. vaadin ---用maven创建vaadin 的工程
  8. Javascript语言精粹--The Excellence in Javascript
  9. 2sk2225代换3A/1500V中文资料【PDF数据手册】
  10. 测试nb信号的软件_NB-IOT测试仪NB测试仪无线网络信号质量检测网络信号故障定位...
  11. QQ邮箱代收Gmail邮箱
  12. C++类内静态成员的内存释放问题
  13. RocketMQ4.0源码分析之-路由管理
  14. EasyExcel自定义表头
  15. 比尔·盖茨表示 AI应被用来改善教育医疗
  16. Ubuntu下bazel卸载与安装
  17. 什么是DNA微阵列技术?
  18. 计算机打音乐两只老虎,两只老虎(音乐、汇编程序)
  19. 网页出现乱码及乱码解决方案
  20. 机器人鸣人是哪一集_博人传:佐良娜因爱开启二勾玉!迪帕是机器人,大蛇丸很怕鸣人?...

热门文章

  1. 作业 校正学生成绩 winform
  2. TreeView节点的演练 c# 1614840318
  3. 办公自动化-演练-统计日报的演练-0223
  4. python环境配置,windows系统,anaconda集成开发环境
  5. dj电商-项目开发流程
  6. django-中间件,视图函数调用前会执行的
  7. JAVA IO系列----ObjectInputStream和ObjectOutputStream类
  8. ASP.NET MVC 4 视图页去哪里儿
  9. 低版本wordpress运行在PHP5.4上如何关闭warning信息
  10. 利用ISA2006发布Exchange的RPC over HTTPS