代码之家  ›  专栏  ›  技术社区  ›  Andrew Cooper

获取在HAPI的请求有效负载中未显示的主体

  •  0
  • Andrew Cooper  · 技术社区  · 8 年前

    我有一个nodejs api服务器正在运行hapi。为了测试,我有一个简单的HTML页面,其中包含一些JavaScript,它使用Fetch来访问API获取一些数据。页面上的javascript如下所示:

     fetch("http://localhost:3000/lov", {
            method: "POST", 
            mode: "cors",
            headers: {"Content-Type": "application/json"},
            body: {P_LOV_NAME: "RTSBLANK"}
    }).then(function(res) {
        return res.json();
    }).then(displayData);
    
    function displayData(data) {
        let elem = document.getElementById("screen");
        elem.innerHTML = JSON.stringify(data, null, 2);
        console.log(data);
    }
    

    问题是HAPI端点似乎没有上述请求的主体。代码如下:

    “使用严格”;

    exports.plugin = {
        name: "LOV",
        version: "1.0.0",
        register: async function (server, options) {
            server.route({
                config: {
                    cors: {
                        origin: ['*'],
                        additionalHeaders: ['cache-control', 'x-requested-with']
                    }
                },
                method: "POST",
                path: "/lov",
                handler: function(request, h) {
                    return getLOV(request, h, server);
                }
            });
        }
    };
    
    function getLOV(request, h, server) {
        console.log("Get LOV Request: ", request.payload);
        let res = server.methods.response();
        res.error = false;
        res.msg = "Retrieved LOV.";
    
        if (request.payload && request.payload.P_LOV_NAME == "RTSBLANK") {
            res.data = server.methods.fake().lovTestUser;
        } else {
            res.data = server.methods.fake().lovBlank;
        }
    
        return res;
    }
    

    在getlov()函数中,request.payload始终为空。我看过请求对象,它上面似乎没有body对象。我有点不知所措,因为这看起来不像一点复杂的代码。我是不是错过了一些明显而愚蠢的东西?

    1 回复  |  直到 8 年前
        1
  •  0
  •   Andrew Cooper    8 年前

    的确,这是一件愚蠢的事情,我忽视了,然后又重新考虑。请求的主体不能是JSON对象。您必须首先对它使用json.stringify()。

    推荐文章