节点其余客户端使用局部变量获取

时间:2018-11-03 15:32:44

标签: javascript node.js rest api node-rest-client

我正在尝试执行以下操作:

var id=9;
            client.get("http://localhost:5000/api/produto/{id}", function (data, response) {
                console.log(data);
                console.log("------------");
                console.log(response);
            });

但是它说:

{ id: [ 'The value \'{id}\'\' is not valid.' ] }

我想知道如何在get请求中使用局部变量? 我正在申请一个已经完成的项目,如果我输入数字而不是ID,它会起作用。

1 个答案:

答案 0 :(得分:2)

尝试

var id=9;
            client.get(`http://localhost:5000/api/produto/${id}`, function (data, response) {
                console.log(data);
                console.log("------------");
                console.log(response);
            });

它称为模板文字:

来自https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

Template literals are enclosed by the back-tick (` `)  (grave accent) character instead of double or single quotes. Template literals can contain placeholders. These are indicated by the dollar sign and curly braces (${expression}). The expressions in the placeholders and the text between them get passed to a function. The default function just concatenates the parts into a single string. If there is an expression preceding the template literal (tag here), this is called a "tagged template". In that case, the tag expression (usually a function) gets called with the processed template literal, which you can then manipulate before outputting. To escape a back-tick in a template literal, put a backslash \ before the back-tick.