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工厂接口路径是什么

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

  1. 平台api对数据收集的影响_收集您的数据不是那么怪异的api

    平台api对数据收集的影响 A data analytics cycle starts with gathering and extraction. I hope my previous blog g ...

  2. 白盒测试基本路径生成工具_基于基本最短路径列生成的车辆路径问题

    论文作者:Alain Chabrier 论文发表日期:2005 摘要 车辆路径问题的列生成模型通常包含一个基本的最短路径子问题.由于该问题已知算法的最坏情况复杂度过高,其基本路径约束通常被松弛.实际上 ...

  3. A股api交易接口文档怎么使用?

    A股api交易接口是在股票量化交易中常用到的一种量化工具,对于它的用法,小编针对性的以文档的例子说明: 交易接口API 功能概述: 名称 功能 基本函数 Init API 初始化 Deinit API ...

  4. 前端请求restful风格接口怎么传参_浅谈Restful API 的请求规范

    前言 在SpringMVC架构上进行开发,开发者一直在使用jsp.valocity或者其他页面模版作为表现层面,前端工程师需要将设计师的设计图转换为静态的html页面,然后交付给后端将静态的html页 ...

  5. api数据接口文档_接口文档示例(Taobao/jd/pinduoduo/开放接口调用)

    api数据接口文档_接口文档示例 本文主要是提供了一个接口文档的范文,内容修订历史.目录.时序图.接口要素描述.接口说明.使用示例.字典.FAQ.  使用MD格式文档(makedown),选择原因,容 ...

  6. java restful接口开发实例_实战:基于Spring Boot快速开发RESTful风格API接口

    写在前面的话 这篇文章计划是在过年期间完成的,示例代码都写好了,结果亲戚来我家做客,文章没来得及写.已经很久没有更新文章了,小伙伴们,有没有想我啊.言归正传,下面开始,今天的话题. 目标 写一套符合规 ...

  7. 微服务之API网关接口设计

    微服务之API网关接口设计 API网关,顾名思义,就是外部到内部的一道门,其主要功能: 服务路由:将前段应用的调用请求路由定位并负载均衡到具体的后端微服务实例,对于前端应用看起来就是1个应用提供的服务 ...

  8. 【开源】.Net Api开放接口文档网站

    开源地址:http://git.oschina.net/chejiangyi/ApiView 开源QQ群: .net 开源基础服务  238543768 ApiView .net api的接口文档查看 ...

  9. 如何用PHP编写简单的api数据接口

    一.编写接口所需几样工具或软件(均是win7+64位) 1.phpStudy.SQLyog和编码工具的安装(sublime text/webStorm/vs code均可,按自己习惯来): 2.启动p ...

最新文章

  1. [恢]hdu 2056
  2. html登录注册的正则,怎么用html5编写用户注册验证程序
  3. php怎么解决雪崩或穿透,Redis之缓存击穿、穿透、雪崩、预热,以及如何解决?...
  4. python常用功能_python----常用功能
  5. 高质量的期货研究报告去哪里找?
  6. GridView - Batch Editing - How to cancel editing or disable the editor conditionally
  7. NanoDet:这是个小于4M超轻量目标检测模型
  8. 一、 Python概述、变量
  9. python匿名函数表达式_在Python中使用lambda表达式进行赋值
  10. java swing窗口放置屏幕中央问题思考
  11. 【Android开发】消息提示框与对话框-使用AlertDialog创建对话框
  12. avaya CM查看VDN指向的技能组
  13. 终于把所有的 Python 库都整理出来啦,赶紧收藏!!!
  14. maven不同环境引用不同版本的jar包依赖
  15. sqlsever2008 函数
  16. 使用python进行北京二手房信息数据分析及可视化展示
  17. Tkinter 极简例子——Event篇
  18. matlab数组 xp,windowsxp系统将matlab数据导入excel的方法
  19. FFMPEG源码编译(Windows篇)
  20. 【转】[Qt教程] Qt串口通信全新专题

热门文章

  1. win7系统如何映射服务器,win7系统如何映射网络驱动器 win7系统映射网络驱动器方法...
  2. 小白声纹识别(说话人识别)探索
  3. Xsell中常用的Linux命令
  4. 基于python机票预定系统_机票预订系统课程设计.doc
  5. 【写作】论文写作技巧
  6. vue3+ts+setup语法糖
  7. 10 分钟把你的 Web 应用转为桌面端应用
  8. Netlink的简单例子
  9. 山经·南山经:杻阳山 [niǔ yáng shān]
  10. 第九讲 Linux I2C子系统及mma8653重力传感器驱动编写