I 'm making a node project and i 'm having trouble when i try to use token result for get request and use it in another get..
how can i use?
thanks!
this is my code:
app.js
.get('/api/v1/token', tokenController.getToken)
.get('/api/v1/search', searchController.getSearch)
Tokencontroller.js
const eventService = require('../services/eventService')
function getToken(req, res){
eventService.getToken()
.then(response => {
console.log(response.body)
const token = response.body.access
console.log(token)
res.send(token)
})
.catch(error => {
console.log('token error')
next(error)
})
}
module.exports = {getToken}
eventService.js
module.exports = {
getToken() {
return new Promise(function (resolve, reject) {
var payload = {
username: 'jon#mail.com',
password: "1111",
grant_type: 'password',
};
request.post({
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + new Buffer.from('user-one' + ':' + '000000000').toString('base64'),
'Accept': 'application/json'
},
url: 'myurl/oauth/token',
form: payload
}, function (error, response, body) {
if (error) {
reject(error)
} else {
resolve({ response , body })
}
});
})
}
now i got the token and i need to pass it to getSearch ..
token response:
{"access_token":"123456","token_type":"bearer","refresh_token":"12345"}
searchController.js
function getSearch(req, res){
eventService.getSearch()
.then(response => {
res.send(response)
})
.catch(error => {
console.log(error)
next(error)
})
}
eventService getSearch
getSearch() {
return new Promise(function (resolve, reject) {
request.post({
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + '123456' //==> token access_token propertie
},
url: 'myurlcontent/search',
}, function (error, response, body) {
if (error) {
reject(error)
} else {
resolve({ response, body })
}
});
})
}
Related
I get the folowing error in the Firebase console : Function execution took 60015 ms. Finished with status: timeout.
Here is my Cloud Function :
exports.test = functions.https.onRequest((req, res) => {
cors(req, res, () => {
const Number = req.body.Number;
return axios.post('https://ws.orias.fr/service?wsdl',
getXMLNS(Number), {
headers:
{ 'Content-Type': 'text/xml' },
},
)
.then((res) => {
return res.status(200).send(res);
}).catch((error) => (error) => {
return res.status(500).send(error);
});
});
});
And here is how I call this Cloud Function in my ReactJS Frontend :
fetch('https://xxx.cloudfunctions.net/test', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
Number: 'xxx',
})
}).then(res => res.json()).then(body => alert(JSON.stringify(body)));
Given is an application for managing users. Following help files are used for this purpose:
AuthenticationAction.js
ManagementAction.js
AuthenticationAction.js is used for authentication:
export function authenticateUser(userID, password) {
console.log("Authenticate")
return dispatch => {
dispatch(getAuthenticateUserPendingAction());
login(userID, password).then(userSession => {
const action = getAuthenticationSuccessAction(userSession);
dispatch(action);
}, error => {
dispatch(getAuthenticationErrorAction(error));
}).catch(error => {
dispatch(getAuthenticationErrorAction(error));
})
}
}
function login(userID, password) {
const hash = Buffer.from(`${userID}:${password}`).toString('base64')
const requestOptions = {
method: 'POST',
headers: {
'Authorization': `Basic ${hash}`
},
};
return fetch('https://localhost:443/authenticate', requestOptions)
.then(handleResponse)
.then(userSession => {
return userSession;
});
}
function handleResponse(response) {
console.log(response)
const authorizationHeader = response.headers.get('Authorization');
return response.text().then(text => {
if (authorizationHeader) {
var token = authorizationHeader.split(" ")[1];
}
if (!response.ok) {
if (response.status === 401) {
logout();
}
const error = response.statusText;
return Promise.reject(error);
} else {
let userSession = {
/* user: data, */
accessToken: token
}
return userSession;
}
});
}
ManagementAction.js is there for the Crud Functions.
export function createUser(userID, username, password) {
console.log("Create a User")
return dispatch => {
dispatch(getShowUserManagementAction());
createaUser(userID, username, password).then(userSession => {
const action = getShowUserManagementActionSuccess(userSession);
dispatch(action);
}, error => { dispatch(getShowUserManagementErrorAction(error)); }).catch(error => { dispatch(getShowUserManagementErrorAction(error)); })
}
}
function createaUser(userID, username, password) {
const token = "whatever"
const requestOptions = {
method: 'POST',
headers: { 'Authorization': `Basic ${token}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ userID: userID, userName: username, password: password })
};
console.log(requestOptions)
return fetch('https://localhost:443/user/', requestOptions)
.then(handleResponse)
.then(userSession => {
return userSession;
});
}
question:
Now if I want to use the createaUser function instead of the hardcoded token value with the accestoken I created in login, how do I get the accesstoken and how do I have to rewrite the createaUser function ?
you can store the token you created in the local storage like this:
AuthenticationAction.js
let userSession = {
/* user: data, */
accessToken: token
}
localStorage.setItem("token", userSession.accessToken)
and you can access it as below:
ManagementAction.js
function createaUser(userID, username, password) {
const token = localStorage.getItem("token")
const requestOptions = {
method: 'POST',
headers: { 'Authorization': `Basic ${token}`, 'Content-Type': 'application/json' },
then
so you can send your token value with the request
I have don't the API check if the token is expired. I have to make a GET call, if I got the 403, error from the API, then I should re-login.
I attempted:
app.get = async (body) => {
return new Promise((resolve, reject) => {
let user = await user.findOne({
where: {
accountId: body.accountId
}
});
if(user){
body.accessToken = user.accessToken;
} else {
body.accessToken = await app.login();
}
request(
{
headers: {
'Accept': 'application/json',
'Authorization': 'Bearer ' + body.accessToken
},
method: 'GET',
uri: `${config.acs.url}${body.url}`,
json: true
}
)
.then((response) => {
resolve(response);
})
.catch((error) => {
// logger.info(error);
if(error.statusCode == 403){
body.accessToken = await app.login(); <<------------- 🐞🐞🐞
app.get(body);
}
reject(error);
});
});
}
I don't know how else to avoid this error.
SyntaxError: await is only valid in an async function
I already have
app.get = async (body) => { ...
I need to re-login only when I get the 403 code in the error block.
How do I re-structure my code to achieve what I described?
The function used in the Promise is not an async function
Try this snippet
app.get = async (body) => {
let resolve, reject;
const promise = new Promise((re, rj) => {
resolve = re;
reject = rj;
});
let user = await user.findOne({
where: {
accountId: body.accountId
}
});
if(user){
body.accessToken = user.accessToken;
} else {
body.accessToken = await app.login();
}
request(
{
headers: {
'Accept': 'application/json',
'Authorization': 'Bearer ' + body.accessToken
},
method: 'GET',
uri: `${config.acs.url}${body.url}`,
json: true
}
)
.then((response) => {
resolve(response);
})
.catch(async (error) => {
// logger.info(error);
if(error.statusCode == 403){
body.accessToken = await app.login(); <<------------- 🐞🐞🐞
app.get(body);
}
reject(error);
});
return promise;
}
I'm working in the integration of a new API endpoint. As a security measure the endpoint expects
in the post request headers:
'x-client-key': 'FRONTEND'
I have been looking around the net , but can't seem to find how to implement in my particular case.
How could I add this in my request?
getMagic(data) {
return new Promise((resolve, reject) => {
this.http
.post(environment.serverUrl + this.getApiEndPoint() + 'get-magic', data)
.subscribe(
(response: any) => {
resolve(response);
},
(err) => {
console.log(err);
reject(err);
}
);
});
}
This is what I've tried but doesn't work...
const headers = new Headers().set('Content-Type', 'application/json').set('x-client-key', 'FRONTEND_CLIENT_KEY ');
return new Promise((resolve, reject) => {
this.http
.post(environment.serverUrl + this.getApiEndPoint() + 'get-geocoding', data, { headers: headers })
.subscribe(
(response: any) => {
resolve(response);
},
(err) => {
console.log(err);
reject(err);
}
);
});
}
I tried also
const headers = new Headers();
headers.set('Content-Type', 'application/json');
headers.set('x-client-key', 'FRONTEND_CLIENT_KEY ');
I assume that you're using Angular, not sure which version, so I'll write a solution for pre-7 and post-7 Angular:
Angular 6 or below:
const headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Access-Control-Allow-Headers': 'Content-Type',
'x-client-key': 'your key'
}
const requestOptions = {
headers: new Headers(headers),
};
return new Promise((resolve, reject) => {
this.http
.post(environment.serverUrl + this.getApiEndPoint() + 'get-geocoding', data, requestOptions)
.subscribe(
(response: any) => {
resolve(response);
},
(err) => {
console.log(err);
reject(err);
}
);
});
Angular 7 or later: replace the class Headers with a class HttpHeaders, docs here.
First, import the HttpHeaders class:
import { HttpHeaders } from '#angular/common/http';
And then refactor your code into:
const requestOptions = {
headers: new HttpHeaders(headers),
};
Solution originally taken from here.
I am facing an issue in converting Audio file to Binary format. I need to send it to Wit.AI api which is expecting the data in that format. I am using node.js. In my front-end I am recording the user voice using Mic-recorder Module. Any suggestions are welcome.
My front end code:
var recorder;
function startRecording() {
recorder = new MicRecorder({
bitRate: 128
});
recorder.start()
}
function stopRecording() {
recorder.stop().getMp3().then(([buffer, blob]) => {
console.log(buffer, blob);
const file = new File(buffer, 'music.mp3', {
type: blob.type,
lastModified: Date.now()
})
console.log(file)
axios({
method: 'post',
url: `${appUrl}/open_api/voice/send?data=${buffer}`
}).then(function (res) {
console.log(res)
if (res.data.success) {
console.log('done',res)
} else {
console.log(res.data)
}
})
})
};
After recording Successfully, I want to send the file to my api in order to call wit.ai /speech api.
My back end code is:
router.post('/voice/send', //chatbot response api
async (req, res, next) => {
let thread_id = '99-99-99-99'
let audioBinary = req.query.data
console.log(audioBinary)
let appId = "5d07621d6b79be66a73f4005"
let sessionId ="10-10-10-10"
let accessToken = await db.model('ChatBotApp').findOne({
_id: req.query.key
}, {
access_token: 1
}).lean()
var options = {
method: 'POST',
uri: 'https://api.wit.ai/speech?v=20190513',
body : audioBinary,
encoding: null,
headers: {
'Authorization': 'Bearer ' + "HY3ZWSUGPBPD5LWZLRSZ3QJCDC27M6EW",
'Content-Type': 'audio/mpeg',
},
// json: true // Automatically stringifies the body to JSON
};
rp(options)
.then(async function (parsedBody) {
console.log('this called',parsedBody)
return
// let response = await firstEntityValue(parsedBody, appId, message, thread_id)
// events.emit('Chats', appId, thread_id, message, sessionId, response);
return res.apiOk(response)
})
.catch(function (err) {
console.log(err)
return res.apiError('Issue while creating app!', err);
})
}
)
var recorder
function startRecording() {
recorder = new MicRecorder({
bitRate: 128
});
recorder.start()
}
function stopRecording() {
recorder.stop().getMp3().then(([buffer, blob]) => {
console.log(buffer, blob);
const file = new File(buffer, 'music.mp3', {
type: blob.type,
lastModified: Date.now()
})
var bodyFormData = new FormData();
bodyFormData.append('file', file);
console.log(file)
axios({
method: 'post',
url: `${appUrl}/open_api/voice/send`,
headers: {
'Content-Type': 'multipart/form-data'
},
data: bodyFormData
}).then(function (res) {
console.log(res)
if (res.data.success) {
console.log('done', res)
} else {
console.log(res.data)
}
})
})
};
API
router.post('/voice/send',upload.single('file'), //chatbot response api
async (req, res, next) => {
console.log(req.file)
let thread_id = '99-99-99-99'
let audioBinary = req.file.buffer
let appId = "5d07621d6b79be66a73f4005"
let sessionId = "10-10-10-10"
let accessToken = await db.model('ChatBotApp').findOne({
_id: req.query.key
}, {
access_token: 1
}).lean()
var options = {
method: 'POST',
uri: 'https://api.wit.ai/speech?v=20190513',
headers: {
'Authorization': 'Bearer ' + "HY3ZWSUGPBPD5LWZLRSZ3QJCDC27M6EW",
'Content-Type': 'audio/mpeg',
},
body: audioBinary
// json: true // Automatically stringifies the body to JSON
};
rp(options)
.then(async function (parsedBody) {
console.log('this called', parsedBody)
return
// let response = await firstEntityValue(parsedBody, appId, message, thread_id)
// events.emit('Chats', appId, thread_id, message, sessionId, response);
return res.apiOk(response)
})
.catch(function (err) {
console.log(err)
return res.apiError('Issue while creating app!', err);
})
})