Node js http 请求:选项中的变量

过氧化氢

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

    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: '\'\'' 
        }
    };

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

异常空指针

为此,您应该使用括号表示法

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);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章