【问题标题】:node.js url search/query portion is emptynode.js url 搜索/查询部分为空
【发布时间】:2017-10-27 11:23:19
【问题描述】:

我正在开发一个在同一台机器上运行的网站(客户端 + 服务器)。 我在chrome的开发者工具中没有发现任何错误,所以我不知道问题出在哪里。

我尝试将一个字符串从客户端发送到节点后端,但在执行时

 url.parse(request.url, true).query

结果为空。

这是我的客户:

var xhttp = new XMLHttpRequest();

xhttp.open("POST", "http://localhost:8080/newComment", true);
xhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhttp.send("val=" + commentString);

我的commentString 是“嘿嘿”

这是我的服务器:

var path = url.parse(request.url).pathname;
else if (path == "/newComment") {

    console.log("query: " + url.parse(request.url, true).body);
    //setNewComment(comment);

    response.writeHead(200, {
        'Content-Type': 'text/plain', 
        'Access-Control-Allow-Origin' : '*',
        'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE'
        }); // enable cors
    response.write("Recieved request");
    response.end();
}

我在网站上

file:///C:/Users/.../website.html?name=hey+there

所以我希望我的节点服务器打印出“查询:嘿那里”,而是打印出“查询未定义”

【问题讨论】:

    标签: javascript html node.js ajax


    【解决方案1】:

    您正在尝试访问正文,这是正确的,但 url 不包含正文的内容,您应该通过侦听“数据”事件来积累它:

    let body = [];
    request.on('data', (chunk) => {
                body.push(chunk);
               }).on('end', () => {
                     body = Buffer.concat(body).toString();
                     // at this point, `body` has the entire request body stored in it as a string
                                   });
    

    或使用“express”和“body-parser”。

    1.进入请求正文部分:https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/

    【讨论】:

    • 谢谢。这很有效,尽管我最终使用了 npm 的 parse-body
    猜你喜欢
    • 2018-02-18
    • 2015-05-12
    • 2017-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多