简体   繁体   English

JavaScript:node.js HTTP GET

[英]JavaScript: node.js HTTP GET

On the HTML side, when I press a button, the following is script is called: 在HTML方面,当我按下按钮时,以下脚本称为:

$("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: 在node.js端,我试图在HTTP请求处理程序中检索名称字段:

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! 如果将数据输入到url中,则可以检索名称字段,即: localhost:1111/html_file.html?name=Mr_Skid_Marks ,但是问题是当我按下按钮时,我没有得到该格式的数据(网址是localhost:1111/html_file.html?任何提示或链接将不胜感激!

Your problem is that you are only looking at the URL ( req.url ) rather than looking at the body of the incoming message. 您的问题是您只查看URL( req.url ),而不查看传入消息的正文。 When the request comes in via a GET request the query parameters are included in the URL. 当请求通过GET请求进入时,查询参数将包含在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. 但是,当请求是POST (例如用户单击表单中的提交按钮时),参数位于请求的正文中。 That means you will need to do something like the example provided at http://nodejs.org/api/stream.html#stream_api_for_stream_consumers . 这意味着您需要执行类似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). 具体来说,您将需要读取正文并从中解析参数,而不是从URL解析参数(因为它们不在URL中)。

Depending on what frameworks you are or aren't using, there may be easier ways to get this information. 根据您使用或不使用的框架,可能会有更简单的方法来获取此信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM