浅谈前端开发过程中使用的代理方法

前端开发过程中解决跨域问题

作为一名前端开发人员,特别是在前后端分离盛行的现在,跨域是不可避免的问题,那么如果你还跑去要后端人员帮你在接口上添加允许跨域的响应头是不是就太low了一点;

众所周知,解决跨域问题的办法有三种,后端设置、JSONP、和代理;这里就给大家讲讲我在开发过程中用过的一些代理;

webpack-dev 自带的代理服务器

单页面开发流行的情况下,如果你的项目是用webpack开发的,那么久好办了,webpack有自带的代理机制;在webpack的config设置文件中有proxy这么一项配置

proxy:{
    "/api":{
        target:"http://127.0.0.1:88",
        secure: false,
        changeOrigin: true
      }
}

在config文件中加上这个配置的话,那么你的项目中要是“/api”的接口都会被代理到”http://127.0.0.1:88/api“这个地址,那么这里你可以写上后端接口的地址;从而在开发的时候就不用跑去麻烦后端人员,也不会有跨域的问题出现;

如果是使用框架的脚手架进行项目搭建,也可以顺着文件的引用关系去找到这个配置在哪个位置,进行修改
比如 vue-cli 中 npm start 的时候引用的webpack 配置文件是build文件下面的webpack.dev.conf;而webpack.dev.conf里面就有一个配置项 proxy: config.dev.proxyTable, config则是引用的 config文件下的index.js ;所以找到对应的位置进行设置就可以了

自己搭建代理服务器

上面的情况是使用webpack自带的代理机制;但是如果在开发过程中没有使用webpack这样开发插件;比如用jquery开发或者原生JS开发过程中遇到了跨域的问题,我们就只能自己想办法搭建一个代理服务器;

nodeJS搭建代理服务器

node.js现在算是前端人员必备的一个知识,因为是javascript中唯一能做后端的语言;它同样能够实现代理机制;不过他的实现方法看起来就没有那么高端
代码如下:

const express = require('express');
const proxy = require('http-proxy-middleware');//引入代理中间件
const app = express();
// Add middleware for http proxying
const apiProxy = proxy('/api', { target: '此处填写代理的目标地址',changeOrigin: true});
app.use('/api/*', apiProxy);//api子目录下的都是用代理
app.listen(63342, () => {
    console.log('Listening on: http://localhost:80');
});

这里我是用webstorm开发工具;63342是webstorm自带的端口;如果开发环境本身与代理服务器也产生了跨域问题;那么久需要在代理服务器上加上允许跨域的响应头

const express = require('express');
const proxy = require('http-proxy-middleware');//引入代理中间件
const app = express();
// Add middleware for http proxying

function onProxyRes(proxyRes, req, res) {
    proxyRes.headers["Access-Control-Allow-Origin"]=" *"; //允许的来源
    //OPTIONS通过后,保存的时间,如果不超过这个时间,是不会再次发起OPTIONS请求的。
    proxyRes.headers["Access-Control-Max-Age"]="86400";
    //!!!之前我碰到和你一样的问题,这个没有加导致的。
    proxyRes.headers["Access-Control-Allow-Headers"]=" Content-Type";
    //允许的请求方式
    proxyRes.headers["Access-Control-Allow-Methods"]=" OPTIONS, GET, PUT, POST, DELETE";

    var method = req.method;
    // OPTIONS请求直接返回成功 此处是处理浏览器出现options请求时的处理逻辑
    if (method === 'OPTIONS')  {
        res.append("Access-Control-Allow-Origin","*");
        res.append("Access-Control-Allow-Headers","Authorization");
        res.status(202).send();
        return;
    }
}

const apiProxy = proxy('/api', { target: 'http://vjd63g.natappfree.cc',changeOrigin: true ,onProxyRes:onProxyRes});
app.use('/api/*', apiProxy);//api子目录下的都是用代理
app.get("/",function(req,res){
    console.log(req);
    res.send("aaa");
});
app.listen(3000, () => {
    console.log('Listening on: http://localhost:3000');
});

docker搭建nginx代理服务器

docker是Linux系统的一个功能;不过在windows系统也可以运行,需要安装虚拟机;windows 10 有自带的虚拟机功能,至于怎么安装我就不多说了,百度Docker 菜鸟教程里面有安装教程

对于docker 本人理解也并不深,只是在开发的时候尝试过用来做代理服务器;
镜像使用nginx官方镜像 把下面的配置文件挂载到nginx的配置文件的default.cong文件;文件位置“/etc/nginx/conf.d/default.conf”
配置文件内容

server {
    listen       80;
    server_name  localhost;

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }
    location /api {
        proxy_pass http://140.143.204.213;
        proxy_ssl_trusted_certificate  conf.d/cert/phpcj.pem;
        proxy_ssl_server_name on;
    }
    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #location ~ \.php$ {
    #    root           html;
    #    fastcgi_pass   127.0.0.1:9000;
    #    fastcgi_index  index.php;
    #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    #    include        fastcgi_params;
    #}

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}
}
location /api {
        proxy_pass http://140.143.204.213;
        proxy_ssl_trusted_certificate  conf.d/cert/phpcj.pem;
        proxy_ssl_server_name on;
    }

这个位置就是代理配置的位置 proxy_pass 是代理目标地址
proxy_ssl_trusted_certificate 如果代理目标是https协议就需要证书;没有证书的话可以不要这一项;但是后面一下必须要有proxy_ssl_server_name on; 开启ssl证书

上面三种代理方法是我在开发过程中遇到过的,可能运用不是很好;希望对大家能有点帮助

猜你喜欢

转载自blog.csdn.net/qq_41114603/article/details/82528811