前端跨域方案-跨域请求代理(node服务)

前端开发人员在本地搭建node服务,调用接口首先走本地服务,然后转发到api站点,node服务代码如下:

var express = require('express'),
    request = require('request'),
    bodyParser = require('body-parser'),

    app = express();
app.use(require('cookie-parser')());
var myLimit = typeof(process.argv[2]) != 'undefined' ? process.argv[2] : '100kb';

app.use(bodyParser());
app.use(express.static(__dirname+'/lingfo'));
app.use('/api', function (req, res, next) {
    
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "GET, PUT, PATCH, POST, DELETE");
    res.header("Access-Control-Allow-Headers", req.header('access-control-request-headers'));

    if (req.method === 'OPTIONS') {
        res.send();
    } else {
        //读取cookie
        var cookie = require('cookie');
        var parse = require('./lib/parse');
        
        var cookies = req.headers.cookie;    //保存对象地址,提高运行效率
        
        req.cookies = cookie.parse(cookies);    //与express中调用cookie.serialize()对应,解析cookie
        req.cookies = parse.JSONCookies(req.cookies);    // JSON字符序列转化为JSON对象
        console.log(req.cookies['token']);
        
        var targetURL = 'http://api.***.com/api';
        if (!targetURL) {
            res.send(500, { error: 'There is no Target-Endpoint header in the request' });
            return;
        }
        var path='';
        if(req.url.indexOf('?')<=0){
            path = req.url+'?token='+req.cookies['token'];
        }
        else{
            path = req.url+'&token='+req.cookies['token'];
        }
        request({ url: targetURL + path, method: req.method, json: req.body, headers: {'Authorization': ''} },
            function (error, response, body) {
                if (error) {
                    console.error('error: ' + response.statusCode)
                }
            }).pipe(res);
    }
});
//定制404页面
app.use(function(req,res,next){
    res.status(404);
});
app.set('port', process.env.PORT || 80);

app.listen(app.get('port'), function () {
    console.log('Proxy server listening on port ' + app.get('port'));
});

node接口代理是在一个github的基础上修改的,增加读取认证cookie然后发送到接口站点实现认证的

参考github地址:https://github.com/ccoenraets/cors-proxy

原文地址:https://www.cnblogs.com/kongkonglonglong/p/6480832.html