用点符号连接变量

Concatenate variable with dot notation

request(`http://127.0.0.1:3000`)
                .post(`${this.apiVersion}${apiEndpoint})
                .set('Accept', acceptType)
                .set('Content-Type', contentType)
                .set('Authorization', authorization)

我有上面的摩卡测试请求。我想对 http 请求使用变量 requestMethod (post, get, put)。

.post(`${this.apiVersion}${apiEndpoint})

就像上面的代码一样,我想使用 requestMethod 变量而不是使用 post 来使其可配置。我如何将点符号与变量连接起来? 我已经用下面的代码试过了,但是没有用。

'.'+requestMethod+'('+ this.apiVersion + apiEndpoint +')'

在 javascript 中,您可以访问作为对象数组索引的属性(奇怪的是,方法)。所以,如果你这样做:

request(`http://127.0.0.1:3000`)[requestMethod](`${this.apiVersion}${apiEndpoint}`)
            .set('Accept', acceptType)
            .set('Content-Type', contentType)
            .set('Authorization', authorization)) 

应该可以。