使用JavaScript在POST方法中传递值

时间:2014-07-24 05:16:22

标签: javascript node.js http-post

这是我的JavaScript功能:我通过谷歌获得此功能。

function postURL() {
    var jobValue = document.getElementsByName('folderName')[0].value;
    url = 'http://localhost:8888/TaaS/Sachin/Input' + "?FolderName=" + jobValue;
    var form = document.createElement("FORM");
    form.method = "POST";
    //if(multipart) {
    form.enctype = "multipart/form-data";
    //}
    form.style.display = "none";
    document.body.appendChild(form);
    form.action = url.replace(/\?(.*)/, function(_, urlArgs) {
        urlArgs.replace(/\+/g, " ").replace(/([^&=]+)=([^&=]*)/g, function(input, key, value) {
            input = document.createElement("INPUT");
            input.type = "hidden";
            input.name = decodeURIComponent(key);
            input.value = decodeURIComponent(value);
            form.appendChild(input);
        });
        return "";
    });
    form.submit();
}

我在onclick期间调用此函数;

<button type="submit" class="btn btn-primary start" onclick="postURL()">
    <i class="glyphicon glyphicon-upload"></i>
    <span>Create Folder</span>
</button>

我在服务器端使用node.js。在服务器端的按钮单击事件期间,POST方法正在调用,但我不知道如何在POST方法期间检索node.js文件中的“jobValue”。

POST方法:

function(req, res) {
    switch (req.method) {
        case 'OPTIONS':
            res.end();
            break;
        case 'POST':
            console.log('req.url: ' + req.url);
            break;
        default:
            res.statusCode = 405;
            res.end();
    }
}

如何在node.js文件中获取该值?

1 个答案:

答案 0 :(得分:3)

您没有指定,但我会假设您在服务器端使用Express。尽管有POST表单,但您在示例中将jobValue作为查询字符串参数(FolderName)发送,因此您可以在处理程序函数中获取它:

req.query.FolderName

在你的回调中:

function(req, res) {
    switch (req.method) {
        case 'OPTIONS':
            res.end();
            break;
        case 'POST':
            var jobValue = req.query.FolderName;  //<-- Your variable
            console.log('req.url: ' + req.url);
            break;
        default:
            res.statusCode = 405;
            res.end();
    }
}
相关问题