Mailgun.Attachment is not a constructor - email

I am sending PDF attachment by using mailgun. When create an instance .
Const attch = new mailgun.Attachment({data:file, filename:filename, contentType: application/PDF});
And run the API it does returned error. "Mailgun.Attachment is not a constructor"

Related

Axios error when sending api request to Discord

I'm trying to send an automated message to discord from my account token using the axios client, it worked on a different project of mine but it doesn't work on a brand new project for some reason. Here is the code so far:
const axios = require('axios').default;
async function Post() {
const URL = `https://discord.com/api/v9/channels/${process.env.CHANNEL}/messages`
const payload = { content: "This message has been sent using axios!" }
await axios.post(URL, payload, { headers: { 'authorization': process.env.TOKEN } })
}
Post();
This is the error I'm getting:
node:internal/errors:464
ErrorCaptureStackTrace(err);
^
TypeError [ERR_HTTP_INVALID_HEADER_VALUE]: Invalid value "undefined" for header "authorization"
at ClientRequest.setHeader (node:_http_outgoing:579:3)
at new ClientRequest (node:_http_client:256:14)
at Object.request (node:https:353:10)
at RedirectableRequest._performRequest (/home/nonce/Documents/Repositories/test/node_modules/follow-redirects/index.js:279:24)
at new RedirectableRequest (/home/nonce/Documents/Repositories/test/node_modules/follow-redirects/index.js:61:8)
at Object.request (/home/nonce/Documents/Repositories/test/node_modules/follow-redirects/index.js:482:14)
at dispatchHttpRequest (/home/nonce/Documents/Repositories/test/node_modules/axios/lib/adapters/http.js:232:25)
at new Promise (<anonymous>)
at httpAdapter (/home/nonce/Documents/Repositories/test/node_modules/axios/lib/adapters/http.js:48:10)
at dispatchRequest (/home/nonce/Documents/Repositories/test/node_modules/axios/lib/core/dispatchRequest.js:58:10) {
code: 'ERR_HTTP_INVALID_HEADER_VALUE'
}
And for the record, I'm not trying to create a spammer or anything that breaks Discord's API rules.
Here are the versions I'm using, if it helps in any way:
node: v16.13.2
npm: v8.1.2
axios: v0.25.0
Found the error, I forgot to add the dotenv package all along.

Bearer Tokens in C++Builder/FMX REST Functionality?

I have a server application running in node.js/Mongoose/MongoDB with a REST interface.
My client application is built in Embarcadero C++Builder/Firemonkey(FMX) and so far all is good with interacting with the node server using the embarcadero REST features (TRESTClient/TRESTRequest/TRESTResponse).
I recently added authentication to my server using JSON Web tokens and the user registration/login is working successfully, giving me back a bearer token using the following code:
const token = jwt.sign({sub: user.id}, process.env.JWT_SECRET, {expiresIn: '30d' })
Accessing data is implemented via express-jwt by sending a REST request with the bearer token. Postman makes it easy to send a request for data using a Bearer token (https://learning.postman.com/docs/sending-requests/authorization/#bearer-token), however I cannot find out how to do this seemingly simple task using Embarcadero's REST features.
I have tried using the Embarcadero REST OAUTH/OAUTH2/SIMPLE/BASIC authentication methods with the bearer token in the Access-Token and Request-Token fields and nothing seems to work.
How can this be done? I am sure this is something simple I am missing but there is next to no documentation I can find.
I figured out an answer for anyone else who is having trouble using authentication in C++Builder with REST:
Design-time method:
--> Setup TRESTClient, TRESTRequest, TRESTResponse
--> In TRESTRequest Params, create a new param with fields:
Name: Authorization, Value: Bearer XXXXXXXX (JWT String), Options: poDoNotEncode (this is the important part
Creating the REST client for authorization at runtime:
// initialize REST client
TRESTClient* pRESTClient = new TRESTClient(BASE_URL);
pRESTClient->ContentType = "application/json";
// connect REST request for querying server
TRESTRequest* pRESTRequest = new TRESTRequest(NULL);
pRESTRequest->Client = pRESTClient;
// connect REST response for receiving JSON from server
TRESTResponse* pRESTResponse = new TRESTResponse(NULL);
pRESTRequest->Response = pRESTResponse;
pRESTResponse->ContentType = "text/html";
// do authenticated query
pRESTRequest->Method = rmGET;
pRESTRequest->Resource = ROUTE_ITEMS;
pRESTRequest->ResourceSuffix = SUBROUTE_ITEMSUFFIX;
pRESTRequest->Params->Clear();
TRESTRequestParameter* param = pRESTRequest->Params->AddItem();
param->Name = "Authorization";
param->ContentType = ctNone;
param->Kind = pkHTTPHEADER;
param->Options << poDoNotEncode;
char temp[512];
sprintf(temp, "Bearer %s", JWT_TOKEN);
param->Value = (const char*)temp;
pRESTRequest->Execute();
The server response is then added to the TRESTResponse->Content field as JSON.
As a note, it is important to have the server configured with express-JWT (https://www.npmjs.com/package/express-jwt) for this to work properly with the following code managing the server (node.js):
app.use(jwt({
secret: process.env.JWT_SECRET,
credentialsRequired: false,
getToken: function fromHeaderOrQuerystring (req) {
if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
return req.headers.authorization.split(' ')[1];
} else if (req.query && req.query.token) {
return req.query.token;
}
return null;
}
}));

GCS Signed URL Post Object using XMLHttpRequest with progress listener results in browser sending Options instead of POST

I have successfully implemented upload of an Object using multi-part Post request with Signature, Policy document GCS POST ...etc from the browser using XMLHttpRequest and angular $http .
But when I attach event listener on XMLHttpRequest upload to show a progress bar to the user, the browser sends a Options Method instead of POST. storage.googleapis.com returns 200 ok After that I was expecting a POST to be sent from the browser with the file but that did not happen. Without the upload listener the code works perfectly. Should I move to PUT ? any workaround
factory.uploadFileToUrlXHR = function(file,obj){
var deferred = $q.defer();
var fd = new FormData();
fd.append('key', obj.key);
fd.append('Content-Type',obj.contenttype)
fd.append('GoogleAccessId', obj.googleaccessId);
fd.append('policy', obj.policy);
fd.append('signature', obj.signature);
fd.append('file', file);
var XHR = new XMLHttpRequest();
XHR.addEventListener('load', function(event) {
// alert('Yeah! Data sent and response loaded.');
deferred.resolve(event);
});
XHR.upload.addEventListener("progress",function(evt){
if (evt.lengthComputable) {
$log.info("add upload event-listener" + evt.loaded + "/" + evt.total);
}
}, false);
// Define what happens in case of error
XHR.addEventListener('error', function(event) {
//alert('Oups! Something went wrong.');
deferred.resolve(event);
});
// Set up our request
XHR.open('POST', obj.uri);
// Send our FormData object; HTTP headers are set automatically
XHR.send(fd);
return deferred.promise;
}
I resolved the issue ,
When you use POST from the browser to upload a file to Google Cloud storage append the bucket name to the URL . In the below code obj.uri should be "https://storage.googleapis.com/bucketname
XHR.open('POST', obj.uri); and remove the bucket name from the key. Key should contain the object name.
fd.append('key', obj.key);
if you do not append the bucket name as part of the POST URL, the browser will send the Options request to https://storage.googleapis.com/. GCS will not be able to find the right CORS configuration. CORS configuration is mapped to the bucket Name.
Sample CORS configuration i had applied.
[
{
"origin": ["http://localhost:8282"],
"method": ["OPTIONS","PUT","POST","GET", "HEAD", "DELETE"],
"responseHeader": ["Content-Type"],
"maxAgeSeconds": 3600
}
]

Getting 'Access denied' when calling REST service

I'm building a small app that consumes a REST service.
The REST service expects that the URL i interact with always have the API key as an URL parameter.
So no matter if i GET, POST, UPDATE or DELETE, my URL should always contain be something like this:
https://rest.service.tld:443/list?api_key=MY-KEY
https://rest.service.tld:443/lists/1/profiles/search?api_key=MY-KEY
I tried with the sample code from RestSharp webpage, but it get the statuscode Access Denied
Here's my code:
// Create client
var client = new RestClient( "https://rest.service.tld:443" );
client.Authenticator = new SimpleAuthenticator( "api_key", "MY-KEY", "", "" );
// GET list of items
var requestLists = new RestRequest( "lists", Method.GET );
IRestResponse<List<ListResponse>> listResponse = client.Execute<List<ListResponse>>( requestLists ); // Returns the correct list
// POST search
var requestProfiles = new RestRequest( "lists/1/profiles/search", Method.POST );
requestProfiles.AddParameter( "Criteria", "{\"email\":\my#email.tld\"}" );
IRestResponse profileResponse = client.Execute( requestProfiles ); // Returns 'Access Denied' status code
As far as i can tell, the POST method doesn't contain the correct querystring, instead my api_key is added as a parameter in the POST.
Is there a way to keep my API_KEY in the Querystring like i need it to be?
By default the api_key is added as a normal parameter, you need to explicitly enforce that you want the parameter to be embedded into the URL, by setting the ParameterType as follows:
var requestProfiles = new RestRequest( "lists/1/profiles/search{api_key}", Method.POST );
requestProfiles.AddParameter( "Criteria", "{\"email\":\my#email.tld\"}" );
requestProfiles.AddParameter( "api_key", MY-KEY, ParameterType.UrlSegment);
More info here

Upload video to Facebook from the server

I have a problem when uploading videos to Facebook.
I use Facebook SDK for Android: https://github.com/facebook/facebook-android-sdk to get the access token with the following permissions: "publish_stream","email","video_upload","publish_actions"
Then I send token to the server, which should upload the video. The server tries to upload video using following code:
string fullurl = string.Format("https://graph-video.facebook.com/me/videos?title={0}&description={1}&access_token={2}", HttpUtility.UrlEncode(fileName), HttpUtility.UrlEncode(description), token);
Facebook returns an error:
System.Net.WebException: The remote server returned an error: (400) Bad Request.
at System.Net.WebClient.UploadFile(Uri address, String method, String fileName)
at System.Net.WebClient.UploadFile(String address, String fileName)
But, when I check token with the following link: https://graph.facebook.com/me?access_token=myToken Facebook returns user info. That means that token is valid. But, if this request returns error code, where I can find information about error codes?
This solution works perfectly for some users, for other users it works unstable ( 4 of 6 videos uploading failed. Facebook returns that: "connection closed by remote server"). And have not worked for some users with error: "The remote server returned an error: (400) Bad Request".
What is wrong in my code?
I've solve the problem. I have start using facebook SDK for .NET http://facebooksdk.net/ and it works for me.
Facebook.FacebookClient fb = new FacebookClient(facebookEditTask.facebookToken);
fb.PostCompleted += (o, e) =>
{
if (e.Cancelled || e.Error != null)
{
return;
}
var result = e.GetResultData();
facebookVideoUrl = CreateLinkToVideo(result.ToString());
};
dynamic parameters = new ExpandoObject();
parameters.source = new FacebookMediaStream
{
ContentType = "video/mp4",
FileName = Path.GetFileName(facebookEditTask.FilePath)
}.SetValue(File.OpenRead(facebookEditTask.FilePath));
parameters.message = fbMessage;
Task t = fb.PostTaskAsync("me/videos",
new { message = fbMessage, parameters.source });