简体   繁体   English

如何根据请求解析原始数据?

[英]How do I parse raw data on request?

I have a form for submitting post data to a database with Ajax that looks like this: 我有一个表单,用于使用Ajax将post data提交到数据库,如下所示:

function markAsRead(id) {
    console.log('Triggered');
    $.ajax({
        type: 'POST',
        url: '/admin/assessment.html',
        data: id,
        success: function(data) {
            if (data.error) {
                console.log('We had an error.');
            } else if (data.success) {
                console.log('Marker updated.');
            }
        }
    })
}

(function() {
    var element = document.getElementsByName('markAsRead');
    for(var i = 0; i < element.length; i += 1) {
        element[i].addEventListener('click', function(e)  { e.preventDefault;
            markAsRead(this.getAttribute('data-value'));
        });
    }
})();

I have multiple Anchors on my page that look like this for example: 我的页面上有多个锚点,例如:

<a href="#" name="markAsRead" data-value="5135135">Mark As Read</a>

I'm just wondering on the Node.js side of things, how might I parse that data, I Tried: 我只是想知道在Node.js方面,我如何解析该数据,我尝试过:

var id = req.body.markAsRead;

  console.log('Data is ' + id);

But it just says undefined. 但是它只是说不确定的。 Any information would be great on how to parse this request data. 关于如何解析此请求数据的任何信息都将非常有用。 Thanks! 谢谢! (The Anchor is not inside any form) Anchor不在任何形式内)

First, you should be POSTing data from the client with named parameters, or something more structured than a string. 首先,您应该使用命名参数或比字符串更结构化的内容从客户端发布数据。

$.ajax({
    type: 'POST',
    url: '/admin/assessment.html',
    data: { id: id },
    success: function(data) {
        if (data.error) {
            console.log('We had an error.');
        } else if (data.success) {
            console.log('Marker updated.');
        }
    }
})

Second, when you parse the req.body on the node side, you're parsing the string that is sent as the request body, which includes your parameters { id: 'somevalue' } . 其次,当您在节点侧解析req.body时,您正在解析作为请求正文发送的字符串,其中包括您的参数{id:'somevalue'} You could parse this yourself, but I'm guessing you're using something like express or another abstraction on top of node's http.Server implementation that supports a middleware stack . 您可以自己解析它,但是我猜您在支持中间件堆栈的节点的http.Server实现之上使用了express或其他抽象之类的东西。 I recommend using the connect bodyParser() middleware, which will convert the req.body string into an object with properties that were posted. 我建议使用connect bodyParser()中间件,它将将req.body字符串转换为具有已发布属性的对象。 This will make req.body.id available to you in your request handler in node. 这将使您在节点中的请求处理程序中可以使用req.body.id。

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

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