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

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的ExpressJava 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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值