• node中间层转发请求


    前台页面:

      $.get("/api/hello?name=leyi",function(rps){
           console.info(rps);
      });
    

    node中间层(比如匹配api开头的所有请求):

    var express = require('express');
    var qs = require("qs")
    var http = require("http");
    var querystring = require('querystring');
    
    app.all(//api/, function(req, res) {
        let strData = qs.stringify(req.body); //请求体中的数据(比如post提交的数据)
        let options = {
            host: 'localhost', //后台请求地址
            port: 8081,
            path: req.url.substr(4),
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Content-Length': strData.length
            }
        };
        options.headers = Object.assign(options.headers, req.headers); //带上客户端请求头(包含cookie之类的东西)
        let httpRequest = http.request(options, function(res) {
            console.log("statusCode: ", res.statusCode);
            console.log("headers: ", res.headers);
            let _data = '';
            res.on('data', function(chunk) {
                _data += chunk;
            });
            res.on('end', function() {
                sendData(_data);
            });
        });
        httpRequest.write(strData); //写入数据到请求主体
        httpRequest.end();
    
        function sendData(data) {
            res.send(data);
        }
    });
    

    node后台:

    var express = require('express');
    var app = express();
    var querystring=require("querystring");
    
    app.post("/hello", function(req, res) {
        console.info("req.headers", req.headers); //node中间层带来的请求头
        console.info("req.query", req.query); //url上的查询参数
        let data = '';
        req.on('data', function(chunk) {
            data += chunk;
        });
        req.on('end', function() {
            data = decodeURI(data);
            console.log("data", data);
            let dataObject = querystring.parse(data);
            console.log("dataObject", dataObject);
        });
        res.json({ "result": "hello world!" });
    });
  • 相关阅读:
    Shipconstructor 2005 破解发布
    活动目录(activate directory)
    上海地铁快成了乞丐天堂
    转载:制造业信息化:计划模拟APS软件驱动敏捷制造
    项目管理的测试版发布
    Introdution RemObject SDK
    怎样在osworkflow中使用BeanShell
    Java class 文件反编译工具 FrontEnd 2.0
    Tribon M3 license keygen
    利用osworkflow实现业务流程
  • 原文地址:https://www.cnblogs.com/leyi/p/9761461.html
Copyright © 2020-2023  润新知