node.js - 如何从已经调用sails js后端的角度应用程序调用微服务(内置express js)?
问题描述
我已经有一个带有角前端和sails js后端的应用程序。但是由于某种原因,我将一些后端功能移到了微服务等单独的快递项目中。但现在我想调用这些函数。请告诉我如何做到这一点。
解决方案
有两种方法可以做到这一点:
CORS
你的微服务应该启用 cors,这样浏览器就不会阻止它的响应。在 Express 中,这可以很简单:
const cors = require('cors'); app.use(cors());
根据天气,端点需要凭据(登录),您可能需要为 cors 设置一些选项:
app.use(cors({ credentials: true, origin: true, methods: 'POST,GET,PUT,OPTIONS,DELETE' }));
请参阅我对另一个问题的回答:Node.js with Angular - CORS error when I send request
查看
cors
中间件的文档以获取配置选项:https ://www.npmjs.com/package/cors应用程序网关
您还可以在Nginx或Apache2或HAproxy等反向代理后面运行所有微服务。这种策略是亚马逊在 2014 年之前(在浏览器实现 CORS 之前)运作的原因。
这是一个用于代理微服务的 Nginx 配置的简单示例:
# The ^~ operator matches all urls that begins with the following string: location ^~ /some/microservice { proxy_pass http://some.microservice.myapp.com; }
将多个微服务映射到单个域名上的 url 路径的反向代理在业界通常称为应用程序网关。应用程序网关还提供额外的好处,例如负载平衡、将内部服务器从 Internet 中设置防火墙等。但就我们的目的而言,使用它的主要原因是允许微服务从与前端代码相同的域中提供服务,这意味着向微服务发出请求不会触发跨域策略。
无论哪种方式,要从您的微服务请求数据,您只需发出一个 ajax 请求。通过老派XMLHttpRequest
或更现代的fetch
API:
// Assuming you've configured CORS correctly on your server:
fetch('https://some.microservice.myapp.com/getdata')
.then(function(response) {
return response.json();
})
.then(function(result) {
console.log(result);
});
// Assuming you are using an application gateway:
fetch('https://myapp.com/some/microservice/getdata')
.then(function(response) {
return response.json();
})
.then(function(result) {
console.log(result);
});
推荐阅读
- python - 使用值作为索引沿新维度折叠一个 numpy 数组
- php - 在 laravel 中找不到页面 404
- java - 如何制作更新类属性的方法?
- angular - Bootstrap 自定义在 Angular 7 中不起作用
- sql-server - 查询仅更新日期时间中的月份
- magento2 - Magento 2.2.7 MAGENTO di:compile 在 1/7 处停止
- javascript - 调用时未调用 Javascript 函数
- python - 导入我的 Python 包时如何允许排除模块?
- javascript - 如何在 API 调用中使用 axios 在 React 中使用异步等待
- python - 如何更新现有的 xml 元素值和属性?