节点js HTTP请求:选项中的变量

时间:2018-08-16 10:46:40

标签: node.js http variables request options

如何将变量传递给请求选项?

    var test = 'name';
    var options = {
        method: 'PUT',
        url: 'someurl',
        headers: {
            'Cache-Control': 'no-cache',
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        form: {
            test: 'Test01',  //<- this should be the variable, not the name of the key
            description: '\'\'' 
        }
    };

我需要通过一些变量动态设置这些键名,但是所有Node都不会接受这些键名,而是将“ test”用作键名。

1 个答案:

答案 0 :(得分:0)

为此,您应该使用bracket notation

options.form[test] = 'Test01';

因此完整的代码应该是

    var test = 'name';
    var options = {
        method: 'PUT',
        url: 'someurl',
        headers: {
            'Cache-Control': 'no-cache',
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        form: {
            description: '\'\'' 
        }
    };

    options.form[test] = 'Test01';
    
    console.log(options);

相关问题