twilio API not sending the repsonse in json format - javascript

I am making an API for sending whatsapp response to client's whatsapp number. I am using twilio as service provider. The problem I am facing is that i am not able to get response in Json. I am following code examples of Twilio
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';
const client = require('twilio')(accountSid, authToken);
client.messages
.create({
from: 'whatsapp:+14155238886',
body: 'Hello, there!',
to: 'whatsapp:+15005550006'
})
.then(message => console.log(message.sid));
According to API documentation. It should return the response in json or xml. but it returns an error and error is not also in json. Socket Hangs up and then nothing happens. API Reference
API
UPDATE:
After Alan's comment. I have added catch block in my code. But still nothing comes up. The API sends request and then everything hangs. After sometime server hangs and the socket hangs up error is thrown by postman console or from Browser.
Updated Code
client.messages
.create({
from: 'whatsapp:+14155238886',
body: 'Hello, there!',
to: 'whatsapp:+15005550006'
})
.then(message => console.log(message.sid)).catch(e =>
{console.error(e.error); });

I have been looking for JSON response from twilio. I couldn't even find in Twilio Documentation yet.
I recommend you to use try catch block
And in your try block you can add a customized JSON response which has a success response with your user defined header.
Default Twilio response will be like below
[Twilio.Api.V2010.MessageInstance accountSid=ACd7c9b4f84efc802cb7bcf8cbeb86b6b9 sid=SMa4d4976f77e844b8a251fcb14e40a855]
You can explode using space(' ') and change to JSON format
In your catch block you can embed catch error in JSON format
I hope this way you can get JSON response

Related

How to catch an error when using S3.getsignedurlpromise() in node.js

I have a node.js server that downloads images from my s3 bucket and serves the images to my React client. I want to manage the case when the wrong file key is sent to the S3 client.
In order to do so, I am intentionally sending a wrong key from React. I am expecting to receive an error that I could catch and render my view accordingly.
Unfortunately, the s3 API is not returning an error, so all the points in my code where I intend to catch the error are being passed and I cant render a view when I get the image and another view when I get an error.
My code looks like so:
//s3Connect.js
download: async (fileKey)=>{
const downloadParams={
Key:fileKey, //this is a wrong key like 123 or anything
Bucket:bucketName
}
const data = s3.getSignedUrlPromise('getObject', downloadParams);
return data
}
//adminPanel.js
//I call the above function below
getBackgroundCheck:async (req,res)=>{
const readStream = await s3.download(req.params.key).then(url=> {
console.log(url)
res.send({url})
})
.catch(error=>{
console.log(error)
res.send('the error is',error) //since I sent a wrong key I expect to catch an error here
} )
}
Now in the client side. I use React and the fetch method to retrieve the image
const getBackgroundFile = async (e) => {
try {
e.preventDefault()
const response = await fetch(`http://localhost:3003/adminPanel/getbackgroundcheck/${id}`)
console.log('this is the response ',response)
const parseResponse = await response.json()
console.log('this is the parseResponse', parseResponse)
setImage(parseResponse)
setShowBackImage(true)
}
catch (error) {
console.log('this is the error',error) //again I expect to see this in console
}
}
Finally:
What do I get with the console.logs from the above function
this is the response Response {type: 'cors', url: 'http://localhost:3003/adminPanel/getbackgroundcheck/nll%C3%B1', redirected: false, status: 200, ok: true, …}
So as you can see I get a 200 status. So how can I manage an error if I get a 200 ok status when I know that the response is failed because my server could not find the image in the s3 bucket and serve it to my client.
Creating a pre-signed URL is an operation that cannot fail, in normal operation. There's no actual API call behind the creation of a pre-signed URL - it's a simple local signing exercise in the SDK. It will happily generate pre-signed URLs for objects that don't exist, for example.
If you wan't to detect vending URLs for non-existent S3 objects, you'll have to do that some other way. For example, by proxying the downloads or pushing responsibility to the client.

Why does a GET request with fetch API log a server response error message into the browser console?

I am using the fetch-API to send a GET request to a Spring Boot backend. The request looks somewhat like this:
const response = await fetch(url);
if (response.status === 200) {
// do something
} else {
response.json().then(response => console.log(response));
}
In case that I send a valid request, i.e. the url passed into fetch() is valid, everything works fine. In case that I pass an invalid url into fetch(), however, two things appear to be happenning:
A serer response message is thrown:
My Spring Boot backend return a ResponseEntity with a custom error message as body. This error message is logged inside the else-block of the above code snippet:
While I do expect the second point to be happenning, I cannot explain the first. I don't understand why this server-response error is logged into my browser console. I do have a few catch-blocks inside my code, something like:
const response = await fetch(url).catch(error => console.log(error));
As far as I know, however, fetch only throws an error if a network connection error occurred or similar. A response code not equal to 200 does not result in fetch throwing an error. So, as I said, I don't know where this error message comes from and I was hoping that somebody does, maybe it is something generic to the fetch API that I just don't know?
I recommend using "try catch" to better capture errors.
If the response is positive and it's a json, use a "then" after the fetch.
try {
const response = await fetch(url).then(res => res.json());
// do something
} catch (e) {
console.error(e);
}
If you're getting a 400 error, check the api documentation to see if you're passing the parameter incorrectly. or if that is not the route

"redirect_uri_mismatch" when sending authentication code to GoogleAPI

I am having trouble with the authentication process for the GoogleAPI. In the end I want to be able to read the users steps using the GoogleFit API and then store that value in a database. Currently I'm using restdb.io and executing javascript in codehooks.
The documentation from Google that I am following can be found here, clicking on the HTTP/REST option in the code examples. At the moment I am at step 5: I have gotten the users authentication code and stored it in the database. Now I have to POST the code along with some other parameters and get the access and refresh tokens.
If the POST is successful (from what I understand) I should get back a 200-OK message that the request was valid. Google will then POST a JSON body with the access and refresh token to the redirect_uri that I have specified in my GoogleAPI credentials page and the initial request. At redirect_uri I have to handle the request and save the two values.
The problem is that I receive a redirect_uri_mismatch - Bad Request message from Google as a response when executing the request. I get it at the log.debug("ERROR HERE: " + [...]); in the code below:
async function mainFunction(){
const authCode = THIS_IS_MY_AUTHENTICATION_CODE;
try {
var answer = await postRequestToGoogle(authCode);
//do stuff with response from Google
} catch (error) {
//do stuff
}
}
async function postRequestToGoogle(authCode){
//body for the request
const params = "code=" + authCode + "&" +
"client_id=THIS_IS_MY_CLIENT_ID" + "&" +
"client_secret=THIS_IS_MY_CLIENT_SECRET" + "&" +
"redirect_uri=THIS_IS_MY_REDIRECT_URI" + "&" +
"grant_type=authorization_code";
try{
const result = await fetch('https://oauth2.googleapis.com/token', {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: params})
.then(res => {
log.debug("ERROR HERE: " + JSON.stringify(res.json()));
return res.json();
})
//return JSON back main function
return result;
}catch(error){
//do stuff
}
}
I looked up the error message and tried some things:
Copy and pasted multiple different Authorized redirect URI from the GoogleAPI credentials page into the code to make sure that there is no problem with
http/https
www/no www
trailing slashes
typos or capitalization
Waited for changes to be processed by Google (read that it can more than 30min)
Changed all the other parameters to see if the redirect_uri is actually the problem
If code is changed the message is invalid_grant - Bad Request
If client_id is changed the message is invalid_client - The OAuth client was not found
If client_secret is changed the message is invalid_client - Unauthorized
If the grant_type is changed the message is unsupported_grant_type - Invalid grant_type
That's why I think the issue is the redirect_uri, but it's unclear to me how since I copy&pasted it. Something that came to mind was that maybe the value of redirect_uri gets changed when it's read by Google? Or maybe when the request is being put together? Do some characters have to be replaced?
I tried to analyze the request with Wireshark but didn't think about the fact that it's HTTPS so I would have I would have to decrypt it.. Is that something I should look into?
Thank you for taking the time to read all of this! If you have any advice please let me know :)
Update 16.11.20:
I have created a new OAuth 2.0 Client ID and used the new id/secret in my request. The resulting message the same as before. I will wait and try again tomorrow to see if maybe Google needs some more time. Then I'll try to delete all current IDs and start with a fresh GoogleAPI project.
Update 19.11.20:
Creating a new OAuth 2.0 Client ID did not resolve my problem, neither did creating a whole new GoogleAPI project and adding those credentials into the request. I am in contact with the developers of restdb.io and have asked them to add the Google Auth Library: Node.js Client to the list of supported Node.js packages. Hopefully that will help, I will give it a try as soon as it can be used :)
Update 02.12.20:
No progress so far, but I'm optimistic that the developers will add the package soon. I will post a final update as soon as I am done with this project.

Unexpected token O in JSON at position 0 when I query an API

I know that the question is findable on the forum but no answer works for me. I have an angular service that calls a nodeJS API like this:
Angular service
public createUser(pUser: User): Observable<User> {
var url = "http://localhost:5000/users";
var json = JSON.stringify(pUser)
return this.http.post<User>(url, pUser)
}
NodeJS API
router.post('/', (req, res) => {
console.log(req.body)
User.create({ email: req.body.email, password: req.body.password })
res.sendStatus(200);
});
The API is well called, the insertion into database works, but I have this message in the browser:
SyntaxError: Unexpected token O in JSON at position 0
The status of the request is 200 on return but the error is still present in the browser
I do not know if the problem comes from the front end or the backend.
After doing some research, I try to parse my object before sending it. I try to stringify too.
Without success
Is this someone would have the solution? thank you very much
This error occurs when you try to parse invalid JSON.
Due to the default response type for angular is JSON and the default response of code 200 is 'OK'. You have to adapt one of them.
You can change the response type to text like this:
this.http.post<User>(url, pUser, {responseType: 'text'});
Or you return a JSON object:
res.status(200).send({ status: 'OK'});
It is good practise to send status 204 (No Content) if You don't send any content in response:
res.sendStatus(204);
Your Angular App should handle it and will not throw an error.
If You send status 200, it's good to add some json object, e.g. {status: "OK"} in res.status(200).send({status: "OK"}). Otherwise You will send the string 'OK' and will get "Unexpected token O ..." (O from 'OK').
From Express doc:
res.sendStatus(200) // equivalent to res.status(200).send('OK')

node.js express send response from variable to the browser and not the console

I am learning node.js
easy to user res.send and some hello world text
but how do I send variables?? to the browser and not the console ??
code example
var Tester = require ('search-google')
, google = new search.Google();
google.list({search parameter,more,more,
})
.then(function (res) {
console.log('results from google', res);
}).catch(function(err) {
console.log('err', err);
});
I tried res write send create server and I still cant understand this
any help much appreciated
Try stringifying the variable before passing to express's send method.
res.send(JSON.stringify(variable));
If the variable is not a string, express sets the contenttype header as json, but you want contenttype header to be html;

Categories

Resources