首页 > 解决方案 > 如何解决未从 Post 请求中获得文本响应的问题

问题描述

我是使用 nodejs 和 javascript 的新手,所以如果我只是做一些明显错误的事情,我很抱歉。我有一个正在运行的 nodejs 应用程序并提供一个 html 页面。该 html 页面可以使用 XMLHttpRequest 发送 Post 请求。请求虽然进行了,但我的节点应用程序调用了我的请求要调用的函数。问题是我想从该请求中获取一些数据,所以我试图从对请求的响应中获取这些数据。问题是我得到一个空洞的回应,我不知道为什么。

这是我的要求。

function SendCachedTriangulation(){
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    document.getElementById('responseLog').textContent = "sent triangulation: " + this.response;
                }
            };
            xhttp.open("Post", "/sendCachedTriangulation");
            xhttp.setRequestHeader("Content-type", "application/json");

            var text = '{ "data" : ' + '{ "someData":"' + '1' + '" } }';

            xhttp.send(text);
            return false;

}

我从中得到的结果是响应为空。它确实更新了我要更新的元素,但它只是说“发送三角测量:”。

在 nodejs 方面,这是我的代码。

router.post('/sendCachedTriangulation', (req, res, next) => {
client.SendCachedTriangulation(() => {    
        res.status(200)
    ;}, req.body
    );       
res.status(200).message = "sent triangulation";
res.send();

});

这似乎是在调用我的函数来正确发送缓存的三角测量我只是没有收到“已发送三角测量”的消息。

我需要更改哪些内容才能在我的 HTML 页面中显示该消息?

标签: javascripthtmlnode.jsrest

解决方案


其实我理解你的片段。我也明白第一次使用 Node 很复杂,因为一切都是 Javascript。让我解释一下:在您的 HTML 中,认为请求是可以的,但实际上有两个文件:执行请求的 HTML 文件和响应请求的节点 HTTP 服务器。所以我的意思是:

// /server/app.js 

router.post('/sendCachedTriagulation', (req, res, next) => { 
      res.status(200).send("sent triangulation") 
}) 

// /client/index.html 

client.SendCachedTriangulation(/* do stuff */)

推荐阅读