api工厂接口路径是什么_为什么(几乎)永远不要再使用绝对路径访问API

api工厂接口路径是什么

by Vitaly Kondratiev

通过维塔利·康德拉季耶夫(Vitaly Kondratiev)

为什么(几乎)永远不要再使用绝对路径访问API (Why you should (almost) never use an absolute path to your APIs again)

Recent advances in web apps architecture show that a decoupled front-end provides more flexibility for development and operations. It

Web应用程序体系结构的最新进展表明,分离的前端为开发和操作提供了更大的灵活性。 它

  • lets you work on one end without depending on the other

    使您可以在一端工作而无需依赖另一端
  • lets you build and deploy separately

    让您分别构建和部署
  • makes it easy to use different tools on each end

    易于在两端使用不同的工具

问题 (The problem)

When an app is developed with this architecture in mind, the front-end needs to communicate to the back-end via APIs, generally REST. Often, the URL/port of the back-end server differs from the front-end’s one, given separate deployment paths. In this example, the URL to the front-end app is https://www.appfocused.com and the REST endpoint to send contact emails is served from https://api.appfocused.com.

当开发应用时要考虑这种架构,前端需要通过API(通常为REST)与后端进行通信。 在给定单独的部署路径的情况下,后端服务器的URL /端口通常与前端服务器的URL /端口不同。 在此示例中,前端应用程序的URL为https://www.appfocused.com ,用于发送联系人电子邮件的REST终结点从https://api.appfocused.com

An HTTP request from the front-end app to the back-end server will fail as it violates the Same Origin Policy. In Chrome’s console it will look like this:

从前端应用程序到后端服务器的HTTP请求将失败,因为它违反了Same Origin Policy 。 在Chrome浏览器的控制台中,它将如下所示:

Browsers, for security reasons, restrict requests which are not from the same origin. This prevents attackers from injecting code into our app and stealing our sensitive information. Browsers append an origin header on cross-origin requests to let the server know of a potential threat. The server then has the authority to either allow or reject these origins by providing specific response headers, which are parsed by the browsers.

出于安全原因,浏览器会限制来自不同来源的请求。 这可以防止攻击者将代码注入我们的应用程序并窃取我们的敏感信息。 浏览器在跨域请求上附加一个origin ,以使服务器知道潜在威胁。 然后,服务器有权通过提供特定的响应头来允许或拒绝这些来源,这些响应头由浏览器解析。

There are two solutions to fix this small problem:

有两种解决此小问题的方法:

  • hardcode absolute API URLs on the client and configure CORS headers on the server

    在客户端上硬编码绝对API URL,并在服务器上配置CORS标头
  • use relative API URLs on the client and use a reverse-proxy approach

    在客户端上使用相对的API URL并使用反向代理方法

In this post, I talk about why the former approach with CORS headers should be considered an anti-pattern for production-ready code. I also talk about how to configure the reverse-proxy approach on various setups:

在本文中,我讨论了为什么以前的带有CORS标头的方法应被视为生产就绪代码的反模式。 我还讨论了如何在各种设置上配置反向代理方法:

  • local devserver

    本地开发服务器
  • web server / app server

    网络服务器/应用服务器
  • serverless (CloudFront / S3 / Lambda)

    无服务器(CloudFront / S3 / Lambda)

基本原理 (Rationale)

The CORS headers scenario sounds like less pain to implement, and it is. However, there are a few concerns to consider that made me preach for the reverse proxy approach under almost any circumstances.

事实证明,CORS标头方案的实现听起来很轻松,而且确实如此。 但是,在几乎所有情况下,都有一些需要考虑的因素使我鼓吹反向代理方法

First and foremost, the back-end might not be owned by you and it might be impossible to make the change to the CORS headers.

首先,后端可能不属于您,并且可能无法更改CORS标头。

If you are lucky enough to control the back-end and can configure CORS headers, you will need to maintain a whitelist of multiple web clients accessing the API server in order to give them access. Of course, wildcard is also an option, but it would be unreasonable to whitelist all the origins by setting access-control-allow-origin to * unless it is a public server.

如果您足够幸运地可以控制后端可以配置CORS标头,则需要维护一个访问API服务器的多个Web客户端的白名单,以便为其授予访问权限。 当然,通配符也是一个选项,但是除非将access-control-allow-origin*除非它是公共服务器,否则将所有来源列入白名单是不合理的。

Another common pattern, during development, is to run our UI application at localhost:$port. But whitelisting localhost to facilitate API calls is an anti-pattern and should be avoided for security reasons.

在开发过程中,另一种常见模式是在localhost:$port运行我们的UI应用程序。 但是将本地主机列入白名单以方便API调用是一种反模式,出于安全原因应避免使用。

Last, but not least, I like my build to conform to the Build Once, Deploy Many principle. It is one of the fundamental principles of continuous delivery. The binary — in our case, static files for the web client — is built only once. Subsequent deployments, testing, and releases should never attempt to build the binary artifacts again. Instead, the already built binary should be reused.

最后但并非最不重要的一点是,我希望我的构建符合“ 一次构建,多次部署”的原则。 这是持续交付的基本原则之一。 二进制文件(在我们的示例中是Web客户端的静态文件)仅生成一次。 后续的部署,测试和发行版绝不应尝试再次构建二进制工件。 相反,应该重新使用已经构建的二进制文件。

In practice, hardcoded absolute URLs like https://api.appfocused.com/email/send in our client code will stop us from having a single artifact, because on development environment I want my web client to hit, say, https://api-dev.appfocused.com/email/send.

实际上,在客户端代码中使用诸如https://api.appfocused.com/email/send这样的硬编码绝对URL会阻止我们拥有单一工件,因为在开发环境中,我希望我的Web客户端点击例如https://api-dev.appfocused.com/email/send

Never hardcode an absolute API URL in your client code.

切勿在客户端代码中对绝对API URL进行硬编码。

This became a powerful mantra for me and helped me to overcome some challenges on the way.

这成为我的强大口号,并帮助我克服了前进中的一些挑战。

(Solution)

The relative URL /email/send can solve it once and for all on the client, making Build Once, Deploy Many possible. It is the proxy’s work to orchestrate the request further. It also deals with the restrictions imposed by the browser. The proxy server, in this case, handles our requests, responses, and makes the modifications necessary to facilitate cross-origin communication.

相对URL /email/send可以在客户端上一劳永逸地解决它,从而使“一次构建,多次部署”成为可能。 代理的工作是进一步协调请求。 它还处理浏览器施加的限制。 在这种情况下,代理服务器处理我们的请求,响应,并进行必要的修改以促进跨域通信。

反向代理与webpack-dev-server (Reverse proxy with webpack-dev-server)

When you are developing on your local machine, you want the same treatment for your API as on other environments. Webpack can be configured to proxy requests. An example “webpack.config.js” is:

在本地计算机上进行开发时,您希望对API的处理与在其他环境中相同。 可以将Webpack配置为代理请求。 示例“ webpack.config.js”为:

module.exports = {//...devServer: {proxy: {'/api': 'http://localhost:9000'}}
};

A request from the client to the relative path /api/users will now proxy the request to http://localhost:9000/api/users. Please check the Webpack documentation if you want to configure URL rewrite scenarios or add secure protocol.

客户端对相对路径/api/users的请求现在会将请求代理到http://localhost:9000/api/users 。 如果要配置URL重写方案或添加安全协议,请查阅W ebpack文档 。

The proxy can also be configured for projects built on Webpack like create-react-app or Gatsby.

还可以为基于Webpack的项目(如create-react-app或Gatsby)配置代理。

NGINX的反向代理 (Reverse proxy with NGINX)

NGINX is a common component in production environment architecture. It has a number of advanced load balancing, security, and acceleration features that most specialized applications lack. Using NGINX as a reverse proxy enables you to add these features to any application.

NGINX是生产环境体系结构中的常见组件。 它具有大多数专业应用程序所缺少的许多高级负载平衡,安全性和加速功能。 使用NGINX作为反向代理,可以将这些功能添加到任何应用程序中。

The simplest reverse proxy config on NGINX will look like this, in “/etc/nginx/conf.d/app.conf”

NGINX上最简单的反向代理配置如下所示:“ / etc / nginx / conf.d / app.conf”

server {listen 80;listen [::]:80;server_name appfocused.com;location /api {proxy_pass http://api.appfocused.com/;}
}

The proxy_pass directive makes this configuration a reverse proxy. It specifies that all requests which match the location block — in this case, /api path — should be forwarded to http://api.appfocused.com, where our back-end is running.

proxy_pass指令使此配置成为反向代理。 它指定所有与位置块匹配的请求(在本例中为/api路径)都应转发到运行后端的http://api.appfocused.com

Check the full docs for some more elaborate scenarios.

查看完整的文档 ,了解更多详细的方案。

无服务器的反向代理 (Reverse proxy with serverless)

We will look at the AWS platform for a serverless scenario. In one of my previous posts I explained how we use serverless architecture to host our website. AWS CloudFront is playing one of the key roles in it, acting as CDN and providing security at the edge for our static files stored on S3.

我们将针对无服务器场景研究AWS平台。 在我以前的一篇文章中,我解释了我们如何使用无服务器架构来托管我们的网站 。 AWS CloudFront在其中扮演着关键角色之一,它充当CDN并在边缘为存储在S3上的静态文件提供安全性。

The first API that we had to integrate into this setup was a contact form. The brief for implementation was the following:

我们必须集成到此设置中的第一个API是联系表单。 实施摘要如下:

When a client posts to https://www.appfocused.com/api/send/email, the request needs to be routed to https://api.appfocused.com/api/send/email where our back-end API is deployed in the form of Lambda function.

当客户发布到https://www.appfocused.com/api/send/email ,请求需要路由到https://api.appfocused.com/api/send/email ,其中我们的后端API以Lambda函数的形式部署。

It turns out that CloudFront supports multiple origin servers. It uses path patterns to determine which origin server to forward requests to. Multiple independent servers, even systems that aren’t inside AWS, can all “own” one or more paths under a single hostname. One of them is the default and owning all the paths not explicitly configured.

事实证明,CloudFront支持多个原始服务器。 它使用路径模式来确定将请求转发到哪个原始服务器。 多个独立的服务器,甚至不在AWS内的系统,都可以在一个主机名下“拥有”一个或多个路径。 其中之一是默认设置,它拥有未明确配置的所有路径。

The concept is very similar to reverse proxies in NGINX or Apache. But the request routing is done by CloudFront, which connects to the appropriate back-end, sends the request, and returns — and possibly caches — the response. It does not redirect the request, so the URL address never changes for the consumer.

这个概念与NGINX或Apache中的反向代理非常相似。 但是请求路由是由CloudFront完成的,CloudFront连接到适当的后端,发送请求,然后返回(可能还缓存)响应。 它不会重定向请求,因此URL地址对于使用者永远不会改变。

CloudFront配置示例 (CloudFront configuration example)

Use the main site’s hostname, for example www.appfocused.com, as the origin. Configure the site’s domain name as an alternate domain name in CloudFront.

使用主站点的主机名(例如www.appfocused.com )作为源。 在CloudFront中将站点的域名配置为备用域名。

Next, add a second origin, with the destination being the hostname where the WP deployment can be reached. Create a behavior with a path pattern that matches /blog* and uses the second origin.

接下来,添加第二个来源,目标是可以到达WP部署的主机名。 创建具有匹配/blog*并使用第二个来源的路径模式的行为。

Our existing CloudFront distribution was set up to point to our static S3 bucket content generated by the great Gatsby. Remember not to use autosuggestion from AWS when creating a new distribution with integration to S3. Manually enter website endpoints similar to this format http://appfocused.s3-website.eu-west-1.amazonaws.com.

我们现有的CloudFront发行版已设置为指向由出色的盖茨比生成的静态S3存储桶内容。 请记住,在创建与S3集成的新发行版时不要使用来自AWS的自动建议。 手动输入类似于以下格式的网站端点 http://appfocused.s3-website.eu-west-1.amazonaws.com

Next, we’ll add our second origin to serve REST requests from API Gateway. From the “Origins” tab select “Create Origin”. Enter the domain name and leave origin path empty. Make sure to select “HTTPS only” for “Origin Protocol Policy”.

接下来,我们将添加第二个来源以服务来自API网关的REST请求。 从“来源”选项卡中选择“创建原点”。 输入域名,并将原始路径留空。 确保为“原始协议策略”选择“仅HTTPS”。

Next go to the “Behaviors” tab and click “Create Behavior” to configure the path.

接下来转到“行为”选项卡,然后单击“创建行为”以配置路径。

For “Path Pattern” we’ll use api/* . This will catch any request starting with /api such as https://www.appfocused.com/api/send/email.

对于“路径模式”,我们将使用api/* 。 这将捕获以/api开头的任何请求,例如https://www.appfocused.com/api/send/email

In the “Origin” dropdown select the Origin we just created. This will ensure that the request will be routed to https://api.appfocused.com/api/send/email.

在“来源”下拉列表中,选择我们刚刚创建的来源。 这将确保将请求路由到https://api.appfocused.com/api/send/email

For “Viewer Protocol Policy” select “HTTPS only”.

对于“查看器协议策略”,选择“仅HTTPS”。

For “Allowed HTTP methods” select “GET, HEAD, OPTIONS, PUT, POST, PATCH, DELETE”.

对于“允许的HTTP方法”,选择“获取,标题,选项,输入,张贴,修补,删除”。

For “Cache Based on Selected Request Headers” select “Whitelist” and add required headers. This prevents the Host Header being passed through to the origin.

对于“基于所选请求标头的缓存”,选择“白名单”并添加所需的标头。 这样可以防止主机头传递到源。

For “Object Caching” select “Use Origin Cache Headers”.

对于“对象缓存”,选择“使用原始缓存头”。

For “Forward Cookies” select “All”.

对于“转发Cookie”,选择“全部”。

For “Compress Objects Automatically” select “Yes”. This will gzip responses.

对于“自动压缩对象”,选择“是”。 这将gzip响应。

CloudFront forwards very few headers to the origin by default. You can configure it to forward what you need, but every header you forward will reduce your cache hit ratio. Personally I’m passing through “Referer”, “Accept”, “Content-Type”, and “Authorization”.

默认情况下,CloudFront会将很少的标头转发到源。 您可以将其配置为转发所需的内容,但是转发的每个标头都会降低缓存的命中率。 我个人是通过“引荐来源网址”,“接受”,“内容类型”和“授权”。

There are some caveats, though, to the serverless proxy on AWS. CloudFront won’t strip paths.

但是,AWS上的无服务器代理有一些警告。 CloudFront不会删除路径。

If a request is sent to https://www.appfocused.com/api/* it will be routed to https://api.appfocused.comwith the /api prefix, not to the root of the site.

如果请求被发送到https://www.appfocused.com/api/*将被路由到https://api.appfocused.com 与该/api网站的前缀,而不是根源。

This can become an issue if you don’t own back-end APIs or, for some reasons, these cannot be changed. If that’s the case, Lambda@Edge comes to the rescue. This service allows you to rewrite paths on the fly, as requests are processed. To configure Lambda@Edge go to CloudFront Behavior item and choose “Lambda Function Associations”.

如果您不拥有后端API,或者由于某些原因而无法更改这些API,这可能会成为一个问题。 如果是这样, Lambda @ Edge可以进行救援。 此服务使您可以在处理请求时即时重写路径。 要配置Lambda @ Edge,请转到CloudFront行为项目,然后选择“ Lambda函数关联”。

结论 (Conclusion)

By implementing reverse proxy across environments we achieve:

通过跨环境实现反向代理,我们可以实现:

  • Secure client-server communication

    安全的客户端-服务器通信

    the identity of your back-end servers remains unknown. This is useful in case of DDoS attacks

    后端服务器的身份仍然未知。 这在DDoS攻击时很有用

  • Build Once, Deploy Many

    一次构建,多次部署

    with relative paths to APIs you can build once, and deploy the same artifact to multiple environments

    通过API的相对路径,您可以构建一次,然后将同一工件部署到多个环境

  • Same Origin

    同源

    a CORS headers configuration on the server is not required

    不需要服务器上的CORS标头配置

My personal advice is: never hardcode absolute paths to your APIs again, unless it is a prototype. Spend a bit more time to configure a reverse proxy layer to make it right.

我的个人建议是:除非它是原型,否则不要再对您的API的绝对路径进行硬编码。 花更多的时间来配置反向代理层以使其正确。

This post was originally published on my company’s blog. Our mission at Appfocused is to help companies execute great user experiences on the web by utilising our vast experience, knowledge of the modern UI trends, best practices, and code craftsmanship.

该帖子最初发布在我公司的博客上。 Appfocused的使命是通过利用我们的丰富经验,对现代UI趋势的知识,最佳实践和代码制作技巧,帮助公司在网络上执行出色的用户体验 。

翻译自: https://www.freecodecamp.org/news/never-use-an-absolute-path-for-your-apis-again-9ee9199563be/

api工厂接口路径是什么

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/392991.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

双机通信c语言程序,上传一个自己编写的I2C双机通信程序

本帖最后由 micro_听海 于 2012-11-24 19:58 编辑这几天一直在搞AVR的twi(twi就是i2c)双机通信程序,使用的是两块arduino开发板。因为最总要这个通信程序最总是要放在winavr的编译环境中,所以没有使用arduino自带的库函数。但是这没关系,因为…

leetcode684. 冗余连接(并查集)

在本问题中, 树指的是一个连通且无环的无向图。 输入一个图,该图由一个有着N个节点 (节点值不重复1, 2, …, N) 的树及一条附加的边构成。附加的边的两个顶点包含在1到N中间,这条附加的边不属于树中已存在的边。 结果图是一个以边组成的二维数组。每一…

Windows Server 2008 部署权限管理RMS

1.1 实战:部署权限管理 试验目的: 在单域环境中部署活动目录权限管理服务,实现文档的保护。 试验环境: ? DCServer安装Windows Server 2008企业版,是ess.com的域控制器,安装企业CA。 ? RMSServer安装Wind…

day5 Python爬虫学习

一 实现京东上的自动搜索并提取信息 from selenium import webdriver # 导入键盘Keys from selenium.webdriver.common.keys import Keys import timedriver webdriver.Chrome()# 检测代码块 try:# 隐式等待,等待标签加载driver.implicitly_wait(10)# 往京东主页…

虚拟dom添加虚拟dom_虚拟DOM缓慢。 认识记忆化的DOM

虚拟dom添加虚拟domby Sindre Osen Aarsaether通过Sindre Osen Aarsaether 虚拟DOM缓慢。 符合已记忆的DOM。 (The Virtual DOM is slow. Meet the Memoized DOM.) 超越虚拟DOM和状态管理 (Moving beyond the Virtual DOM and State Management) The virtual DOM was a fantas…

编写一个字节数的rtu C语言校验程序,Modbus通信协议中CRC校验的快速C语言算法

Modbus通信协议中CRC校验的快速C语言算法2004年第11期            福 建 电 脑  63Modbus通信协议中CRC校验的快速C语言算法孟开元(西安石油大学计算机学院陕西西安710065)【摘 要】 本文主要讨论了Modbus通信协议的RTU帧格式中常用的错误校验方法,即循环冗…

leetcode1319. 连通网络的操作次数(并查集)

用以太网线缆将 n 台计算机连接成一个网络,计算机的编号从 0 到 n-1。线缆用 connections 表示,其中 connections[i] [a, b] 连接了计算机 a 和 b。 网络中的任何一台计算机都可以通过网络直接或者间接访问同一个网络中其他任意一台计算机。 给你这个…

Codeforces 600E Lomsat gelral (树上启发式合并)

题目链接 Lomsat gelral 占坑……等深入理解了再来补题解…… #include <bits/stdc.h>using namespace std;#define rep(i, a, b) for (int i(a); i < (b); i)typedef long long LL;const int N 600010;int n; int cc[N], col[N], sz[N], son[N]; LL ans[N];vect…

如何让CloudStack使用KVM创建Windows实例成功识别并挂载数据盘

问题产生背景&#xff1a; 使用CloudStack KVM组合进行资源池纳管工作&#xff0c;通过ISO镜像文件创建了两个模板&#xff1a; RHEL6U3 64位系统以及WindowsServer2008 R2 SP1 64位系统。然后通过模板创建实例&#xff0c;挂载外接存储&#xff0c;实例启动后&#xff0c;通过…

云计算openstack介绍

转载于:https://www.cnblogs.com/WIU1905/p/11107593.html

C语言Node lt T gt,c语言论坛填空;#includelt;stdio.hgt;# 爱问知识人

填空&#xff1b;#include #include #define N 6typedef struct node {int data;struct node *next;填空&#xff1b;#include #include #define N 6typedef struct node {int data;struct node *next;} NODE;void fun(NODE *h){ NODE *p, *q; int t;/**********found*********…

gitlab设置邮件服务器_如何设置您自己的一次性电子邮件服务器

gitlab设置邮件服务器by Oren Geva由Oren Geva 如何设置您自己的一次性电子邮件服务器 (How To Setup Your Own Disposable Email Server) Disposable email services are online services that provide temporary email addresses for registering or signing up on websites…

leetcode442. 数组中重复的数据

给定一个整数数组 a&#xff0c;其中1 ≤ a[i] ≤ n &#xff08;n为数组长度&#xff09;, 其中有些元素出现两次而其他元素出现一次。 找到所有出现两次的元素。 你可以不用到任何额外空间并在O(n)时间复杂度内解决这个问题吗&#xff1f; 示例&#xff1a; 输入: [4,3,2…

C语言基础注意点

一、基础知识篇 &#xff08;一&#xff09;关键字 1&#xff0c;存储类型 A、auto 声明自动变量&#xff0c;一般不使用 B、static 声明静态变量 C、extern 声明变量是在其他文件正声明&#xff08;可看做引用变量&#xff09; D、register 声明积有器变量 2、常用…

**加密解密基础、PKI及SSL、创建私有CA**

进程间通信 socket通信 客户端-->请求--> 路由转发 --> 服务端&#xff0c;取出资源 --> 封装为可响应给客户端的请求报文从接收请求端口发出 SSL/TLS协议的实现 OpenSSL OpenSSL程序组件 1234[rootlocalhost CA]# rpm -ql openssl /usr/lib/libcrypto.so.10 //加…

json 文件打读取

1。获取文件路径 /** BookController.class.getClassLoader().getResource("static/json/book_nav.json").getPath() 获取当期运行时的项目json文件路径*/JSONObject json JsonResourceUtils.getJsonObjFromResource(BookController.class.getClassLoader().getReso…

16F877A和24C02通信汇编语言,pic单片机IIC通信读24C02程序例 16F877A 主频4M

#define _iic_h_//pic单片机IIC通信初始化函数声明void iiccsh(void);//pic单片机IIC通信读外围设备函数声明//功能&#xff1a;传送一个8位地址&#xff0c;返回一个8位数据unsigned char iicread(unsigned char data);//pic单片机IIC通信给外围器件发送函数声明//功能&#x…

如何从XMLHttpRequest创建自定义获取API

What is your worst nightmare?你最可怕的噩梦是什么&#xff1f; That sounded dark, but it’s not a rhetorical question. I really want to know because I am about to tell you mine. Along the way, we will learn some things like how the fetch API works and als…

leetcode637. 二叉树的层平均值

给定一个非空二叉树, 返回一个由每层节点平均值组成的数组。示例 1&#xff1a;输入&#xff1a;3/ \9 20/ \15 7 输出&#xff1a;[3, 14.5, 11] 解释&#xff1a; 第 0 层的平均值是 3 , 第1层是 14.5 , 第2层是 11 。因此返回 [3, 14.5, 11] 。/*** Definition for a b…

5.3 上午

观看英语课程——《恋练有词》 学习Linux 转载于:https://www.cnblogs.com/bgd140206110/p/6801164.html