zoukankan      html  css  js  c++  java
  • nodejs实现请求代理

    通常我们常用的请求方法只有GET、POST、PUT和DELETE,所以在此只介绍这四种和文件上传的代理方式

    在此我们使用request.js第三方模块实现

    GET(DELETE同GET,将request方法改为DELETE即可)

        const request = require('request');
        const url = require('url');
    
        test: function (req, res, next) {
            let curl = url.parse(req.url);
            let search= curl.search;
            curl = "http:/localhost:8080/api/get"+search;
    
            try {
                req.pipe(request({
                    method: 'GET',
                    uri: curl
                })).pipe(res);
    
            } catch (e) {
                next(e);
            }
        }
    

      

    POST(PUT同POST,将request方法改为put即可)

        const request = require('request');
        const url = require('url');
    
        test: function (req, res, next) {
            let curl= url.parse(req.url);
            let search= curl.search;
            curl = "http://localhost:8080/api/post"+search;
    
            let body = req.body;
            try {
                request.post({
                    uri: curl,
                    form: body
                }).pipe(res);
    
            } catch (e) {
                next(e);
            }
        }
    

      

    代理文件上传

        const request = require('request');
        const url = require('url');
    
        upload: function (req, res, next) {
            let curl= url.parse(req.url);
            let search= curl.search;
            curl = "http://localhost:8080/api/upload"+search;
    
            try {
                req.pipe(request({
                    method: 'POST',
                    uri: curl
                })).pipe(res);
    
            } catch (e) {
                next(e);
            }
        }
    

      

        

  • 相关阅读:
    java-工具代码
    idea-常用快捷键
    idea-环境配置
    mysql-常用命令
    Java IO流学习总结
    Java类加载机制
    Struts2标签 %{ } %{# }详解
    EL语法
    SQL语句
    在servlet转向jsp页面的路径问题
  • 原文地址:https://www.cnblogs.com/zhen-rh/p/7474542.html
Copyright © 2011-2022 走看看