在同一个域中分离后端和前端应用程序? [英] Separate back-end and front-end apps on same domain?

查看:53
本文介绍了在同一个域中分离后端和前端应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在使用 Play 框架构建一个完全 RESTful 的后端.我们还在构建一个单独的 Web 前端,其中包含将调用 RESTful API 的不同技术堆栈.

We are building a fully RESTful back-end with the Play Framework. We are also building a separate web front-end with a different technology stack that will call the RESTful API.

我们如何部署这两个应用,使它们具有相同的域名,其中一些 url 用于后端 API,一些用于前端视图?

How do we deploy both apps so they have the same domain name, with some url's used for the backend API and some for the front-end views?

例如,访问MyDomain.com 意味着前端显示主页,但是向MyDomain.com/product/24 发送GET 意味着后端返回带有产品信息的JSON 对象.另一种可能性是,如果 Web 浏览器查看 MyDomain.com/product/24,那么前端会显示一个 HTML 页面,并且该网页是通过后端调用相同的 url 构建的.

For example, visiting MyDomain.com means the front-end displays the home page, but sending a GET to MyDomain.com/product/24 means the back-end returns a JSON object with the product information. A further possibility is if a web browser views MyDomain.com/product/24, then the front-end displays an HTML page, and that webpage was built from a back-end call to the same url.

最后,我们需要两台专用服务器吗?或者可以将前端和后端部署在同一台服务器上(例如 OpenShift、Heroku)

Finally, do we need two dedicated servers for this? Or can the front-end and back-end be deployed on the same server (e.g. OpenShift, Heroku)

推荐答案

你要深入挖掘自己...... :)

毫无疑问,最简单和最干净的方法是创建一个为 BE 和 FE 提供数据的单一应用程序,您可以通过 URL、伪路由来区分响应(JSON 与 HTML):

You are gonna to dig yourself... deep :)

Simplest and most clean approach with no any doubt is creating a single application serving data for both, BE and FE, where you differ response (JSON vs HTML) by the URL, pseudo routes:

GET  /products/:id          controllers.Frontend.productHtml(id)
GET  /backend/products/:id  controllers.Backend.productJson(id)

优点:

  • 单一部署(比如 Heroku)
  • 由一个应用管理的名称空间
  • 更改其中之一后无需修改许多应用程序中的模型

如果你真的决定创建两个独立的应用程序,使用一些 HTTP 服务器作为代理 - 例如 nginx - 这样它就会将所有请求发送到 domain.tld/* 到在端口 9000 上工作的应用程序(它将用 HTML 回答)但对 domain.tld/backend/* 的请求重定向到在端口 上工作的应用程序>9001 使用 JSON 响应.

If you're really determined to create a two separate apps, use some HTTP server as a proxy - for an example nginx - so it will send all requests to domain.tld/* to application working at port 9000 (which will answer with HTML) but requests to domain.tld/backend/* redirect to application working at port 9001 responding with JSON.

如果您真的要根据调用者使用 JSON 或 HTML 进行响应,您可以尝试比较标头以检查请求是从浏览器发送的还是从每个控制器中的 AJAX 调用发送的,但相信我,这将比你这东西……投币,选口味

If you are really gonna to response with JSON or HTML depending on the caller you can try to compare headers to check if request was sent from browser or from AJAX call in each controller , but believe me that will become a nightmare faster than you thing... insert the coin, choose the flavor

这篇关于在同一个域中分离后端和前端应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆