How to log Mocha/Chai HTTP requests - ecmascript-6

Hi I am new to Mocha/Chai.
I am trying to test some HTTP requests. If would be nice if I could log the actual test request to debug it.
The code I am using looks something like
describe('Get token for super user', () => {
it('it should get a valid token set', (done) => {
let req = chai.request(app)
req
.get('/oauth/token')
.set('Content-Type','application/x-www-form-urlencoded')
.set('Authorization','Basic blah')
.field('grant_type', 'password')
.field('username', superUser)
.field('password', superPass)
.end((err, res) => {
console.log('*******' , req)
res.should.have.status(200)
done()
})
})
})
How would I log the request itself, I don't see a neat way of doing this from the API docs ?

Simplest way to get and log all info about request - response object:
chai.request('http://...')
.post('/endpoint')
.send('{"a":1}')
.end((err, response) => {
console.log(response);
done();
});

Related

get real-time json data from twilio runtime with axios

I am trying to achieve real-time data from twilio server-less function. I am using a boilerplate function edited a little bit.What I want is json data in server and voice response in call consecutively .but the following code is not sending json data to server.
const axios = require('axios');
exports.handler = function (context, event, callback) {
let twiml = new Twilio.twiml.VoiceResponse();
twiml.say('you are welcome ');
const instance = axios.create({
baseURL: 'http://fafc4eac4162.ngrok.io/',
timeout: 3000,
});
instance
.post('/test', {
id: 1,
title: 'Twilio'
})
.then((response) => {
console.log(JSON.stringify(response.data));
})
.catch((error) => {
console.log(error);
return callback(error);
});
return callback(null, twiml);
};
It shows below error,but it sends data successfully if I do not use the voice response callback return callback(null, twiml) and rather use simple return callback(null, response.data);
{"message":"timeout of 3000ms exceeded","name":"Error","stack":"Error: timeout of 3000ms
exceeded\n at createError (/var/task/node_modules/axios/lib/core/createError.js:16:15)\n
at RedirectableRequest.handleRequestTimeout
(/var/task/node_modules/axios/lib/adapters/http.js:280:16)\n at Object.onceWrapper
(events.js:286:20)\n at RedirectableRequest.emit (events.js:198:13)\n at
Timeout._onTimeout (/var/task/node_modules/follow-redirects/index.js:166:13)\n at
ontimeout (timers.j...
The return callback(null, twiml); should be in the .then block.
.then((response) => {
console.log(JSON.stringify(response.data));
return callback(null, twiml);
})
Also, the error indicates the 3000ms timeout is hit, is your application returning a 200-OK?

Api GET request returns an empty response but postman does not

I am trying to make an api call to a remote server, Initially, I got this error: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I temporarily solve this error by attaching the https://cors-anywhere.herokuapp.com link before the link, or sometimes using the Moesif Cors-Any-where chrome extension. The fetch now returns 200 ok status but the response is empty.
body: ReadableStream
locked: true
__proto__: ReadableStream
bodyUsed: true
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"
response: {}
data: undefined
However, if I run the same query on postman, it returns the expected response json object. How do I fix this?
const searchFlightData = (to, from, depDate, adults) => {
fetch(`http://api.travelpayouts.com/v1/prices/direct?origin=${from}&destination=${to}&depart_date=2017-11&return_date=2017-12&token=${tp_token}`)
.then(response => {
if (response.ok) {
console.log(response)
return response
}
else
console.log(`Looks like something went wrong. Status: ${response.status}`)
})
.then(response => {
response.json()
console.log("response: " + JSON.stringify(response))
})
.then(data => {
console.log("data: " + data)
})
.catch(error => {
console.log(error)
})
}
response.json() returns a promise, you have to wait for resolving this. you also have to return something if you want the next then in the chain to receive something.
something like this should work:
const searchFlightData = (to, from, depDate, adults) => {
fetch(`http://api.travelpayouts.com/v1/prices/direct?origin=${from}&destination=${to}&depart_date=2017-11&return_date=2017-12&token=${tp_token}`)
.then((response) => {
if (response.ok) {
return response
} else {
throw `Looks like something went wrong. Status: ${response.status}`;
}
})
.then(response => response.json())
.then(data => {
console.log("data: " + data)
})
.catch(error => {
console.log(error)
})
}
or with your console.log:
return response.json().then((data) => console.log(data));
Add A Header For accept all as follow in the front-end request
if you want to request data from a server it has to be on the same domain, or the 'Access-Control-Allow-Origin' header has to be set.
I wont rely on a service like https://cors-anywhere.herokuapp.com
For development you can use a proxy server to bypass this limitation. (many frameworks already have a solution for this, i don't know which one you use)
I know this is a very old question, but I've got exact same problem last night. The issue was the SSL connection, which is enforced by Chrome and is not enforced by Postman. So just make sure your API can handle https protocol.

Stripe Error Message 405 - "append .json to uri to use rest api"

I'm using Stripe, and trying to send a test webhook to my URL and database hosted by Firebase. When I "send test webhook," I get the following error message in the Stripe Console:
Test Webhook Error: 405
"append .json to your request URI to use the rest API"
My code is a direct copy of the tutorial: https://github.com/GaryH21/Stripe-Webhooks-Tutorial/blob/master/functions/index.js
Here is the code of my index.js:
const functions = require('firebase-functions');
const stripe = require("stripe")(functions.config().keys.webhooks);
const admin = require('firebase-admin')
admin.initializeApp();
const endpointSecret = functions.config().keys.signing;
exports.events = functions.https.onRequest((request, response) => {
let sig = request.headers["stripe-signature"];
try {
let event = stripe.webhooks.constructEvent(request.rawBody, sig, endpointSecret)
return admin.database().ref('/events').push(event)
.then((snapshot) => {
return response.json({ received: true, ref: snapshot.ref.toString() })
})
.catch((err) => {
console.error(err)
return response.status(500).end() // error saving to database
})
} catch (err) {
return response.status(400).end() // signing signature failed
}
})
exports.exampleDataBaseTrigger = functions.database.ref('/events/{eventId}').onCreate((snapshot, context) => {
return console.log({
eventId: context.params.eventid,
data: snapshot.val()
})
})
The only time in the tutorial and in my code that .json is used is in the line: return response.json({ received: true, ref: snapshot.ref.toString() })
Should I be appending .json onto "request" somewhere, such as in request.RawBody?
It isn't a problem with the signing keys, as that would give the 400 Error message, which I already dealt with and fixed.
I would be happy to share the code of other files in my app, but as far as I can tell none of the rest is relevant to the problem. Thank you very much.

Angular2 Http.Post - How to view webapi response

I'm new to Angular2/Typescript and I'm writing my first web application.
I'm trying to call a webapi using POST, it works, if I intercept the call using FIDDLER I can see the Json response.
Now, how I can log in the browser console the json ouput?
The code is this:
code call
var s = this.myService.doSearch();
s.subscribe(
data=> this.data = data,
error => this.errorMessage = <any>error
);
console.log(s);
service method
doSearch() {
var url = this.baseUrl;
return this.http.get(url)
.map(response => response.json())
.catch(this.handleError);
}
My question is: how and where I can view and manage the Json Output ?
Thanks
You need to console.log it after the async code is finished:
var s = this.myService.doSearch();
s.subscribe(
data=> {
this.data = data;
console.log(data);
},
error => this.errorMessage = <any>error
);
If you are debug or run your application in browser you can got to inspect and then move to the Network tab. In this tab select your POST Request and the go to the tab Response and voila there is your json Response
Edit:
To log all response data do this:
return this.http.get(url)
.map(res => res.json())
.subscribe(data => { console.log(data);})
.catch(this.handleError);
}
Try this this will print what you have in your returned observable .
var s = this.myService.doSearch();
s.subscribe(data=> {
this.data = data;
console.log(data);
},
error => this.errorMessage = <any>error
);
Always remember If you want to get data from observable.you need to subscribe it.
you can't log it like this console.log(s); because s returns an observable. you should subscribe and refer those data inside the subscribe .

Express Multiple res.json(); with middlewares

I'm trying to build a stateless API using JWT. I have a middleware function in my Router which checks if the JWT has expired, if it has, a new Token with a new timestamp is generated on the fly.
I would like to pass the new token along with the response in the JSON Object. My current approach is like this, but it of course doesn't work:
router.use(function (req, res, next) {
// JWT Expired
// Generate new JWT
res.write(JSON.stringify({token: token});
next();
});
router.get('/securedRoute' function(req, res) {
// Fetch data
res.json({data: data});
});
:
// Output should be:
{token: 'erg34jlkgjre.3f4fknlj.34f3', data: ['sdfa', 'sdf']}
It would be nice to find a way, where I don't have to alter all of my existing code and check if there is a new token.
Thanks for your help!
One option would be to add the authorization token in the response header:
router.use((request, response, next) => {
response.setHeader('Token', token);
next();
});
router.get('/securedRoute', (request, response) => {
response.json({ data: data });
});
Alternatively, you could always add the token to the request and then conditionally add the request.token into all of your routes like the previous answer suggested. Unfortunately that would mean that you need to modify all of your routes.
As an alternative you could override the response.json method and manually inject the token if it exists. In doing so, you wouldn't need to modify any of your routes.
router.use((request, response, next) => {
request.token = token;
((proxied) => {
response.json = function (data) {
if (request && request.token) {
data.token = request.token;
}
return proxied.call(this, data);
};
})(response.json);
next();
});
router.get('/securedRoute', (request, response) => {
response.json({ data: data });
});
In the example above, the response.json method is overridden in the middleware. This is done by passing a reference to the old response.json method and then calling it after conditionally injecting the token into the payload.
The answer is assuming you want to achieve that in same method
Rather than writing the token in middleware do something like
(req,res,next)=>{
req.token = newToken;
next();
}
And in your route
res.json(req.token ? {token:req.token,data:data} : {data:data});