Retrieve access_token from console log using Mocha - javascript

I can get the entire response log using console.log(res) but can't retrieve access_token from it. The response containing access_token looks like this:
accept: [Array],
'content-length': [Array]
}
},
text: '{"access_token":"eyJhbGciOiJS....
I've tried the following:
.end( function (res, err, access_token, refresh_token) {
if (err) console.error(err);
else {
console.log(res)
expect(res).to.have.status(200);
//console.log(res.body)
const token = JSON.stringify.access_token;
// token = res.access_token;
console.log(token)
// let accessToken = await auth.getAccessToken();
// console.log(accessToken);
// assert(accessToken != null, 'token is null');
//var token = body.access_token
//console.log(token + "see on token");
// console.log(`options.access_token: ${options.access_token}`);
This is what I'm getting
UPDATE: By using the below code, parsing and using stringify I'm able to log out the token, but I'm still not able to use the parsed in the next request as header, getting undefined
chai.request(uaaUrl)
.post('/oauth/token')
.set('Content-Type', 'application/x-www-form-urlencoded')
.set('Accept', '*/*',)
.send(Authuser)
.end(function(err, res, body) {
const eurotoken = JSON.parse(JSON.stringify(res.body.access_token));
console.log('parsedd token', eurotoken);
expect(res).to.have.status(200)
done();
})
it('./health', (done) => {
let eurotoken;
chai.request(euro_url)
.get('/request-statuses')
.set('Content-Type', 'application/x-www-form-urlencoded')
.set('Accept', '*/*',)
.set('Authorization', `Bearer ${eurotoken}` )
.end( function (res, err, body) {
if (err) console.error(err);
else {
expect(res).to.have.status(200)
done();
}
done();
})
});

Related

Can't authorize user in jwt - Node.js react.js

When user login , it should redirects to homepage and gets posts.
I make api call in react but it returns 401 unauthorized . If I do with same auth header on postman it returns proper data.
const getPosts = async () => {
await axios
.get("/api/post", {
headers: { authorization: "Bearer" + localStorage.getItem("token") },
})
.then((res) => setPosts(res.data));};
useEffect(() => {getPosts();},[]);
Server Side
router.get("/api/post", authToken, async (req: Request, res: Response) => {
const posts = await Post.find({ relations: ["user"] });
return res.json(posts);
});
middleware
const authToken = (req: Request, res: Response, next: NextFunction) => {
const token = req.headers.authorization?.split(" ")[1];
if (token == null) return res.sendStatus(401);
jwt.verify(token, "SECRET", (err, decode) => {
if (err) return res.sendStatus(403);
res.locals = { ...res.locals, token: decode };
next();
});
};
You are missing the whitespace in your headers:
headers: { authorization: "Bearer " + localStorage.getItem("token") }

How to get front-end data in the backend using vanilla Node Js

I know it's possible to get data sent by the user in the back-end using Express.js which is:
router.get("/pathName", async function(req, res){
count = req.body;
})
But how to do this in vanilla (pure) Node.js itself?
Here's an example of a simple server.
const http = require('http');
http
.createServer((req, res) => {
res.writeHead(200, {
'Content-Type': 'text/html',
});
switch (req.url) {
// http://localhost:8080/
case '/':
res.write('<h1>Home</h1>');
break;
// http://localhost:8080/page
case '/page':
res.write('<h1>Page</h1>');
break;
}
res.end();
})
.listen(8080);
Also, here's an example (probably incomplete in terms of all edge cases...) of getting JSON data from a request payload:
const http = require("http");
// server that only supports POST /count
// expects JSON data to be passed like { "count": 100 }
// must have application/json content type header and POST method
http
.createServer(async (req, res) => {
// ensure method is content type json, POST, and /count
if (
req.headers["content-type"] != "application/json" ||
req.url !== "/count" ||
req.method !== "POST"
) {
res.writeHead(404, {
"Content-Type": "application/json",
});
res.write(JSON.stringify({ message: "Unsupported route" }));
res.end();
}
// try to read body
let body;
try {
body = await readBody(req);
} catch (err) {
res.writeHead(400, {
"Content-Type": "application/json",
});
res.write(JSON.stringify({ message: err.message }));
res.end();
}
// try to parse body
let parsedBody;
try {
parsedBody = JSON.parse(body);
} catch (err) {
res.writeHead(400, {
"Content-Type": "application/json",
});
res.write(JSON.stringify({ message: err.message }));
res.end();
}
// make sure count property is present in parsed body
if (typeof parsedBody.count === "undefined") {
res.writeHead(400, {
"Content-Type": "application/json",
});
res.write(JSON.stringify({ message: err.message }));
res.end();
}
// create response
res.writeHead(200, {
"Content-Type": "application/json",
});
res.write(JSON.stringify({ message: "Got " + parsedBody.count }));
res.end();
})
.listen(8080);
function readBody(req) {
return new Promise((res, rej) => {
let body = "";
req.on("data", (data) => {
body += data;
});
req.on("end", () => {
res(body);
});
req.on("error", (err) => {
rej(err);
});
});
}
Cool to see how it works for learning. But if you're using it for a project, I'd highly recommend Express or another framework/lib as you'll find it will get quite painful to try to consider all various cases you will need. Frameworks like Express are quite light anyway.

Can not download file while sending request from one node.js server to another

I am facing some issue while downloading file using node.js. I have scenario like my angular component is sending the file request. in my first node server I am doing the token validation and then redirecting to another node server where actually the execution happens. I am explaining my code below.
service.ts:
submitAndDownloadFile(formdata : any ){
const token = localStorage.getItem('token')
let headers = new HttpHeaders({
Authorization: 'Basic ' + token
})
const cecID = localStorage.getItem('cec');
const AppUrl = `${environment.nodeJsBaseUrl}:${environment.hostingNodeJsContainerPort}/convert-test-cases/${cecID}`;
return this.httpClient.post(AppUrl, formdata, { responseType: 'blob', observe : 'response', headers : headers});
}
Here I am sending the request to my first node.js server which code has given below.
app.js(first:port-8000):
router.post('/convert-test-cases/:id', middleware.auth, (req, res) => {
try{
let postRequestOptions = {
url: '',
method: 'POST',
json: true,
headers: {},
body: {},
};
postRequestOptions.url = 'http:localhost:9000/convert-test-cases';
postRequestOptions.headers = {
'Content-Type': 'application/json',
};
postRequestOptions.body = req.body;
request(postRequestOptions, async (error, response, pathList) => {
if(error) {
console.log('error', error);
}else{
res.send(pathList);
}
})
}catch(e){
responseObj = {
status: 'error',
msg: 'Error occurred while processing your request',
body: null
}
return res.send(responseObj);
}
})
Here I am doing the token validation using middleware.auth and sending same request to another node.js file which code is explained below.
app.js:(second-port-9000):
router.post('/convert-test-cases', async (req, res) => {
try{
let response = await ctcCtrl.convertTestCase(req.body, req.files);
if(response.status == 'success'){
res.set('Access-Control-Expose-Headers','*, Content-Disposition');
return res.download(response.fileName,response.fileName);
}else{
return res.send(response);
}
}catch(e){
responseObj = {
status: 'error',
msg: 'Error occurred while processing your request',
body: null
}
return res.send(responseObj);
}
})
Here only I am doing some execution and downloading the file. If I am connecting angular to node-9000 its working fine but my requirement is first I have to connect to port-8000 to some token validation and after that I have to send same req.body and re.file to app.js which is running in 9000 using request module. As per my code its not working at all.

Axios request to Gmail API unauthorised error?

I have tried to send, with Google API and Axios, a new email:
async SendMail (req, res) {
try {
const email = `From: ${req.body.sender}\r\n` + `To: ${req.body.receiver}\r\n` + `Subject: ${req.body.subject}\r\n\r\n` + req.body.message
const response = await axios.post(`https://www.googleapis.com/upload/gmail/v1/users/${req.body.userId}/messages/send`, email, {headers: {Authorization: `Bearer ${req.body.token}`, 'content-type': 'message/rfc822'}})
res.status(200).send({data: response.data, status: 'ok'})
} catch(err) {
console.log('error => ', err)
res.status(404).send({
error: 'Error for the recuperation of Google info'
})
}
}
It tells me I am unauthorised but I have added the correct scopes.
error: {
response: {
status: 401,
statusText: 'Forbidden',
...
}
}
The accessToken is working I have done a call with a get with it and it worked pretty fine.
This is my scope: https://mail.google.com/

difference between api call and on postman

I was using Azure Speech rest api. And i tried it on post man with a .wav file and it successfully return the result. However, when i call api from my node.js code. It always return Unsupported Audio Format even though i give the same audio file. Can anyone tell me what's the difference of them? Or what did Postman do to make it work?
Below is how i call speech api by node.js.
'use strict';
const request = require('request');
const subscriptionKey = 'MYSUBSCRIPTIONKEY';
const uriBase = 'https://westus.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=en-US';
const options = {
uri: uriBase,
body: 'speech.wav',
headers: {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key' : subscriptionKey,
'Transfer-Encoding': 'chunked',
'Expect': '100-continue',
'Content-type':'audio/wav; codec=audio/pcm; samplerate=16000'
}
};
request.post(options, (error, response, body) => {
if (error) {
console.log('Error: ', error);
return;
}
let jsonResponse = JSON.stringify(JSON.parse(body), null, ' ');
console.log('JSON Response\n');
console.log(jsonResponse);
});
You can try this
fs.readFile('/path/to/my/audiofile.wav', function (err, data) {
if (err) throw err;
var options = {
host: 'https://westus.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=en-US',
method: 'POST',
headers: { 'Content-Type': 'audio/wav' }
};
var req = http.request(options, function(res) {
// Handle a successful response here...
});
req.on('error', function(e) {
// Handle an error response here...
});
// Write the audio data in the request body.
req.write(data);
req.end();
});

Categories

Resources