zoukankan      html  css  js  c++  java
  • 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!" });
    });
  • 相关阅读:
    AC3 encoder flow
    AC3 IMDCT
    AC3 Rematrix
    AC3 channel coupling
    AC3 mantissa quantization and decoding
    AC3 bit allocation
    AC3 exponent coding
    C# 判断字符串为数字 int float double
    vs 修改默认的调试浏览器
    visio 如何扩大画布大小
  • 原文地址:https://www.cnblogs.com/leyi/p/9761461.html
Copyright © 2011-2022 走看看