记录:前后端拆分后的组合

  最近设计架构时,有个场景,首先是前后端分离,再就是一前端对多后端,这里需要解决两件事,一是前端的html,js,css需要一个host;二是需要一个api网关,能组织后端的api服务。有很多反向代理产品能实现,这里选择了Nginx来实现。

记录:前后端拆分后的组合

 

  下面是在一个前端的html文件中调用后端api的例子,前端是不知道后端的api是不是组合的,所以只用相对路径请求就ok

<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>


<script src="axios.min.js"></script>
<script>
function getServiceA(){
axios.get('/service_a/test')
  .then(function (response) {
     var x=document.getElementById("a")
     x.innerHTML=response.data;
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
}

function getServiceB(){
axios.get('/service_b/test')
  .then(function (response) {
   var x=document.getElementById("b")
     x.innerHTML=response.data;
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
}
</script>

<button onclick='getServiceA()'>Get Service A</button><span id="a"></span>
</br>
</br>
<button onclick='getServiceB()'>Get Service B</button><span id="b"></span>

</body>
</html>

下面nginx的配置

worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server {
        listen       8484;
        server_name  localhost; 
        location / {
            root   html;
            index  index.html index.htm;
        }    
    #-------
    location /service_a/ {
       proxy_pass http://localhost:5001/;
    }
    location /service_b/ {
       proxy_pass http://localhost:6001/;
    }
    #-------     
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

其实的A服务,B服务相似

namespace NginxTest1.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class TestController : ControllerBase
    {
        private readonly ILogger<TestController> _logger;
        public TestController(ILogger<TestController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public string Get()
        {
            var str = "ServiceA:5001_" + DateTime.Now;
            _logger.LogInformation(str);
            return str;
        }
    }
}

运给的结果

记录:前后端拆分后的组合

 

 关于前后端服务的部署,就随便了,可虚机,可docker

 

  想要更快更方便的了解相关知识,可以关注微信公众号    记录:前后端拆分后的组合

 

 

上一篇:解决ifconfig查看没有ens33


下一篇:go: go.mod file not found in current directory or any parent directory; see ‘go help modules‘