我正在尝试使用运行在node.js 8.1上的lambda从alexa后端代码访问外部API,该代码可以访问不需要api键的任何终结点,但是我找不到包括我的authoraztion的方法( api键)中的代码,这样我就可以检索我正在寻找的数据。 我试图访问的api文档如下:
curl --request GET -H'授权:承载'-H'内容类型:application / json'“ https://some-end-point/path/i/want”
这是针对alexa-skills-kit的,它在调用该技能后使用lambda,并尝试通过api-key访问外部api。代码可以将信息检索到不需要任何键的任何端点。 我已经尝试过将密钥作为参数包含在URL中(api密钥+ URL),因为alexa,lambda,nodejs不熟悉,因为我不确定如何调试它,但我只是没有得到期望的输出(这是alexa转换文本)与从外部api获取的信息进行语音交流。
pd:假设我的api密钥是:xxxx-xxxx-xxxx
// endpoint that i want
url = https://some-end-point/path/i/want
await getRemoteData(url)
.then((response) => {
const data = JSON.parse(response);
outputSpeech = `the data thati want is ${data.records.length} `;
for (let i = 0; i < data.records.length; i++) {
if (i === 0) {
//first record
outputSpeech = outputSpeech + data.records[i].fields.name + ', '
} else if (i === data.records.length - 1) {
//last record
outputSpeech = outputSpeech + 'y '+data.records[i].fields.name +
', '
} else {
//middle record(s)
outputSpeech = outputSpeech + data.records[i].fields.name + ', '
}
}
})
//function getRemoteData
const getRemoteData = function (url) {
return new Promise((resolve, reject) => {
const client = url.startsWith('https') ? require('https') : require('http');
const request = client.get(url,(response) => {
if (response.statusCode < 200 || response.statusCode > 299) {
reject(new Error('Failed with status code: ' + response.statusCode));
}
const body = [];
response.on('data', (chunk) => body.push(chunk));
response.on('end', () => resolve(body.join('')));
});
request.on('error', (err) => reject(err))
})
};
上面的代码可以访问任何端点而没有错误,但是我不知道如何包括api密钥,因此它可以访问api,预期的输出是通过包含api-key可以访问api
这个新手会很高兴为这个问题提供任何帮助....
答案 0 :(得分:0)
您需要传递一个express.static
对象作为const fs = require("fs");
var parseUrl = require('parseurl')
app.use((req, res, next) => {
var originalUrl = parseUrl.original(req)
var path = parseUrl(req).pathname
// make sure redirect occurs at mount
if (path === '/' && originalUrl.pathname.substr(-1) !== '/') {
path = ''
}
// We only answer to GET
if (req.method !== 'GET' && req.method !== 'HEAD') {
return next()
}
let path = path;
fs.exists(path, (exists) => {
if(!exists)
{
// file don't exists skip this middleware
return next();
}
fs.readFile(path, (err, data) => {
if (err)
{
// Can't send the file skip this middle ware
return next();
}
// Do whatever you need with the file here?
// ...
// Setup mime type of the file
res.setHeader("content-type", "text/html");
// send the client the modified html
res.send(data);
});
console.log(exists ? 'it\'s there' : 'no passwd!');
});
});
的第二个参数。例如:
options
然后在哪里进行请求:
client.get
您可以在const options = {
headers: {
'Authorization': 'Bearer <your API key>'
}
}
here上找到更多详细信息。