weixin_33743248 2014-04-14 17:05 采纳率: 0%
浏览 49

JavaScript:node.js HTTP GET

On the HTML side, when I press a button, the following is script is called:

$("form").submit(function(f) {
    f.preventDefault();
    $.ajax({
        url: "/example",
        data: "name=Mr_Skid_Marks",
        type: "GET",
        success: function(data) {
            //do something with data
        },
        error: function(e) {
            //bad news
        }
    });
});

On the node.js side, I am trying to retrieve the name field in the HTTP request handler:

var queryData = url.parse(req.url, true).query;
var nameVal = queryData.name;

response.setHeader('Content-Type', 'application/json');
response.end(JSON.stringify({name: nameVal}));

I able to retrieve the name field if the data is typed into the url, ie: localhost:1111/html_file.html?name=Mr_Skid_Marks, but the problem is when I press the button I do not get the data in that format (the url is localhost:1111/html_file.html? Any tips or links would be appreciated!

  • 写回答

1条回答

  • weixin_33695450 2014-04-14 17:28
    关注

    Your problem is that you are only looking at the URL (req.url) rather than looking at the body of the incoming message. When the request comes in via a GET request the query parameters are included in the URL. However, when the request is a POST (like when a user clicks the submit buttons in a form), the parameters are in the body of the request. That means you will need to do something like the example provided at http://nodejs.org/api/stream.html#stream_api_for_stream_consumers. Specifically, you will need to read the body and parse the parameters from that rather than parsing them from the URL (since they aren't in the URL).

    Depending on what frameworks you are or aren't using, there may be easier ways to get this information.

    评论

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办