前端解决请求后台服务出现跨域的两种方案

背景介绍:前端在对接后台服务的时候,经常会出现跨域问题,在此,提供两种解决方案

**

1.nginx**

简介:Nginx是一款轻量级的Web 服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,在BSD-like
协议下发行。其特点是占有内存少,并发能力强,事实上nginx的并发能力在同类型的网页服务器中表现较好,中国大陆使用nginx网站用户有:百度、京东、新浪、网易、腾讯、淘宝等。

1、nginx 添加server


worker_processes  1;

events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;

    server {
        listen       8887;
        server_name  localhost;

    
        location / {
            root   html;
            index  index.html index.htm; 
            proxy_set_header   Host    $host;
            proxy_set_header   X-Real-IP   $remote_addr;
			
        }

        location /api/ {                                             ##                     
            proxy_pass http://192.168.50.105:8000/;                  ##   此三行为关键
        }                                       					 ##
		
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

2.前端请求接口(请求端口与nginx端口一致,nginx为中间层,前端请求到nginx,nginx进行代理转发,api会被nginx 中/api/ 所匹配到,然后进行转发到http://192.168.50.105:8000/ 上)
在这里插入图片描述
在这里插入图片描述
真实的后台接口为 http://192.168.50.105:8000/enforcementDetail

2.node.js

简介:Node 是一个让 JavaScript 运行在服务端的开发平台,它让 JavaScript 成为与PHP、Python、Perl、Ruby 等服务端语言平起平坐的脚本语言。 [2] 发布于2009年5月,由Ryan Dahl开发,实质是对Chrome V8引擎进行了封装。

1.http-proxy 插件

注:以下为node.js中所用到的代码,前端请求方式同上。

const httpProxy = require('http-proxy');
const express = require("express");
const app = express();

const targetUrl = `http://192.168.50.105:8000`;
const proxy = httpProxy.createProxyServer();

app.use('/api',(req,res)=>{
    proxy.web(req,res,{target:targetUrl})
});

猜你喜欢

转载自blog.csdn.net/qq_32341603/article/details/103888554