【发布时间】:2018-08-29 20:56:02
【问题描述】:
我想做的事:
1) 使用我的 .json 文件发布到我的 API(包含我需要的整个正文)
2) 在 .json 文件中,我想使用像 ${value} 这样的变量,然后从我的 .js 文件中获取该值并替换 .json 文件中的 var
- 目前使用带 Mocha 的 NodeJS。我有我的 API 调用(下面的 .js 代码):
// for brevity - I removed the other dependencies
const jsonconfig_post = require('./POST.json'); // this is my .json file
describe('\nPOST <TO MY ENDPOINT> \n', function() {
const apiBase = `<MY ENDPOINT>`;
const cookieJar = request.jar();
var nameDate = new time.Date();
beforeEach(function(done) {
this.timeout(5000);
common.verifyLogin(cookieJar, done); //calls my login code
});
it('POST 1: <MY ENDPOINT> - POST', function(done) {
const title = 'NodeJS_Project';
let requestBody = jsonconfig_post(title + nameDate);
//NodeJS_Project is the Var name and nameDate is the appended date
this.timeout(5000);
const opts = {
jar: cookieJar,
uri: `${apiBase}/<MY ENDPOINT>`,
method: 'POST',
json: true,
headers: {
"Content-Type": "application / json",
"Accept": "text / json"
},
body: (requestBody), // POST to my API with this
};
request(opts).then(() => {
opts.body = {};
console.log(requestBody);
done();
}).catch(done);
});
});
- 我的 POST.json 文件 - 如下。我想使用 ${title} 并将其替换为我的 .js 代码中的内容 - “NodeJS_Project”。
{
"title": "${title}",
"Id": "<SOME ID>"
}
学习 NodeJS/Mocha 并且到目前为止非常喜欢它。我可以在使用 .json 文件之外完成这项工作 - 但是使用 .json 文件使事情变得更容易就 .js 的外观而言,例如简单干净。这是一个小例子 - 其他 POST 调用使用了一个巨大的 json 主体(许多嵌套元素),因此在这种情况下使用 .json 非常有价值,例如替换 .json 文件中的许多变量/值。我知道这可以工作,我希望?我目前得到 400 并且可以看到 JSON 没有正确传递到端点 - 或者 - 我只是发布了变量 ${title} (不是我想要的)。任何帮助都会非常感激。 注意 - 我已经尝试了许多其他使用 JSON.parse/stringify 等的方法,但都失败了 - 或者 - 我没有正确使用(肯定可能是这种情况:))。 提前致谢 干杯! -E
【问题讨论】:
标签: json node.js mocha.js interpolation string-interpolation