zoukankan      html  css  js  c++  java
  • 前端跨域方案-跨域请求代理(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

  • 相关阅读:
    Visual Studio Ultimate 2012 RC win8 Metro应用的一个小bug样式继承
    windows 8 MSDN Examples 中一个奇怪的问题
    升级到IE9变成英文版的解决办法
    windows phone 中 TextBox 的诡异事件 TextChanged
    Windows Phone(OS7.1)中常用控件继承关系
    在Ubuntu使用gcc编译的程序无法运行的问题。
    Jquery实现简单图片切换
    div ul li 加a 错位问题
    asp.net mvc 2.0 数据验证
    asp.net mvc 2 (.net 4.0) “检测到有潜在危险的 Request.Form 值”的解决方法
  • 原文地址:https://www.cnblogs.com/kongkonglonglong/p/6480832.html
Copyright © 2011-2022 走看看