JavaScript:node.js HTTP GET


                    

在HTML端,当我按下按钮时,以下脚本称为:</ p>

  $(“ form”)。submit(function(f){
     f.preventDefault();
     $ .ajax({
         网址:“ / example”,
         数据:“名称= Mr_Skid_Marks”,
         类型:“ GET”,
         成功:功能(数据){
             //对数据做点什么
         },
         错误:function(e){
             //坏消息
         }
     });
});
</ code> </ pre>

在node.js端,我试图在HTTP请求处理程序中检索名称字段:</ p>

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

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

如果将数据键入url,我可以检索名称字段,即: localhost:1111 / html_file.html?name = Mr_Skid_Marks </ code>,但是问题是当我按下按钮I时 不要以这种格式获取数据(网址为 localhost:1111 / html_file.html?</ code>任何提示或链接将不胜感激!</ p>
     </ div>

展开原文

原文

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个回答


您的问题是您仅查看URL( req.url </ code>),而不查看传入消息的正文。 当请求通过 GET </ code>请求进入时,查询参数将包含在URL中。 但是,当请求是 POST </ code>时(例如用户单击表单中的提交按钮时),参数位于请求的正文中。 这意味着您需要执行 http://nodejs.org/api/ stream.html#stream_api_for_stream_consumers 。 具体来说,您将需要读取主体并从中解析参数,而不是从URL解析参数(因为它们不在URL中)。</ p>

根据您正在使用或未使用的框架,可能会有更简单的方法来获取此信息。</ p>
     </ div>

展开原文

原文

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.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐