首页 > 解决方案 > 如何从已经调用sails js后端的角度应用程序调用微服务(内置express js)?

问题描述

我已经有一个带有角前端和sails js后端的应用程序。但是由于某种原因,我将一些后端功能移到了微服务等单独的快递项目中。但现在我想调用这些函数。请告诉我如何做到这一点。

标签: node.jsangularexpresssails.jsmicroservices

解决方案


有两种方法可以做到这一点:

  1. 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

  2. 应用程序网关

    您还可以在NginxApache2HAproxy等反向代理后面运行所有微服务。这种策略是亚马逊在 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或更现代的fetchAPI:

// 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);
  });

推荐阅读