在nodejs中,我能够成功进行POST请求并获得API密钥。我需要重新使用此API密钥,以通过GET进行进一步的请求。如何在后续的GET请求中重复使用从初始POST请求获得的apiKey结果?
任何帮助将不胜感激。谢谢!
var request = require('request');
var uri = 'example.com';
var user = 'user';
var pass = 'password';
var token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9";
//POST
request.post(
{
headers: {'content-type' : 'application/x-www-form-urlencoded'},
url: uri,
rejectUnauthorized: false,
form: { email: user, username: user, password: pass, trustToken: token }
},
function(err, httpResponse, body) {
if (err) {
return console.error('post failed:', err);
}
var obj = JSON.parse(body);
//authToken = json.data.authToken;
//userId = json.data.userId;
console.log('Post successful! Server responded with:', body);
var keys = Object.keys(obj);
apiKey = obj[keys[0]];
}
);
//GET
var Token = {{apiKey}};
console.log(Token);
const options = {
url: 'https://example.com/ask/search/docs',
method: 'GET',
headers: {
'Accept': 'application/json',
'Accept-Charset': 'utf-8',
'User-Agent': 'my-reddit-client'
},
form: {
apiToken: {{apiKey}},
question: "change probability",
stopWords: "false",
language: "en",
start: "0",
rows: "2",
project:{"projectId":"1752","projectName":"Mars"}
}
};
request(options, function(err, res, body) {
let json = JSON.parse(body);
console.log(json);
});
答案 0 :(得分:0)
您可以在请求标头中设置密钥,并随每个请求一起发送。
const options = {
url: 'https://example.com/ask/search/docs',
method: 'GET',
headers: {
'Accept': 'application/json',
'Accept-Charset': 'utf-8',
'User-Agent': 'my-reddit-client',
'x-auth-token': Token
},
form: {
question: "change probability",
stopWords: "false",
language: "en",
start: "0",
rows: "2",
project:{"projectId":"1752","projectName":"Mars"}
}
};
然后,您基本上可以在服务器上使用代码作为中间件,以从请求中提取代码并对请求进行身份验证。
您可以将令牌保存在会话存储中。如果您打算使令牌(如Facebook等)保存多天,则可以使用HTTP安全cookie。