I am using firefox addons sdk.
I have created a plugin and I wanted to send request out of it. I came across following code on Mozilla developer site.
var Request = require("sdk/request").Request;
var latestTweetRequest = Request({
url: "https://api.twitter.com/1/statuses/user_timeline.json?screen_name=mozhacks&count=1",
onComplete: function (response) {
var tweet = response.json[0];
console.log("User: " + tweet.user.screen_name);
console.log("Tweet: " + tweet.text);
}
});
// Be a good consumer and check for rate limiting before doing more.
Request({
url: "http://api.twitter.com/1/account/rate_limit_status.json",
onComplete: function (response) {
if (response.json.remaining_hits) {
latestTweetRequest.get();
} else {
console.log("You have been rate limited!");
}
}
}).get();
Here I cannot get any option to pass credentials along with request. As long as it is possible I want to avoid passing credentials along with url e.g. http://username:password#example.com, because many time special characters in password creates issue. So how to pass credentials with this request.
var { encode, decode } = require("sdk/base64");
// use encode() to base64 encode your credentials
var encodedCredentials = encode(email + ':' + password);
var testRequest = FRequest({
url: url,
headers: {
'Authorization': 'Basic ' + encodedCredentials
},
onComplete: function(response){
addOnPanel.port.emit('event', response.json)
}
}).get();
Related
I am using AJAX to download the excel file from server. But the downloaded data is different from actual data
Actual data is with orange background. Received data is in yellow background.
From the difference file, it looks like they are using different encoding formats. So excel throws error that the file is not in correct format.
$.ajax({
url: exporting.action,
headers: { "Authorization": "Basic " + btoa("key : " + key) },
type: "post",
responseType: "arraybuffer",
success: function (res, status, obj) {
var blob = new Blob([str2ab(res)], { type: obj.getResponseHeader('Content-Type') });
var objectUrl = URL.createObjectURL(blob);
window.open(objectUrl);
},
data: { 'Model': JSON.stringify(modelClone) }
});
Please help to resolve this
The trouble with "encoding" is caused that jQuery did not response arraybuffer but string. Strings are in JavaScript UTF-16 and binary data in string cause trouble next to trouble. I recommend you to use native AJAX instead of jQuery. Code is similar and browser support is the same as the browser support of blobs and object URLS what you use.
var xhr = new XMLHttpRequest();
xhr.open("POST", exporting.action);
xhr.setRequestHeader("Authorization", "Basic " + btoa("key : " + key));
xhr.responseType = "arraybuffer";
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var blob = new Blob([xhr.response], { type: xhr.getResponseHeader('Content-Type') });
var objectUrl = URL.createObjectURL(blob);
window.open(objectUrl);
}
}.bind(this);
xhr.send({ 'Model': JSON.stringify(modelClone)});
I'm attempting to post interactive messages to slack as a Bot User (using chat.postMessage, etc).
Although I am passing in the Bot Access Token (as received from the initial OAuth) I keep getting an error response stating "not_authed".
I get the same when I attempt auth.test.
I'm doing something like the following with "request" in node.js:
app.get("/testAuth/test", function(req,res){
console.log("in testAuth/test...sending test message to Slack");
var bToken = process.env.TESTBOT_ACCESS_TOKEN;
var slackMessageURL = "https://slack.com/api/auth.test";
var postOptions = {
uri: slackMessageURL,
method: "POST",
token: bToken
};
request(postOptions, (error, response, body) => {
if(error){
console.log("OOPPPPS....we hit an error in auth.test: " + error);
} else {
console.log("auth.test response: " + JSON.stringify(response));
}
});
res.send("Sent Test...check logs");
});
which results with:
auth.test response: {"statusCode":200,"body":"{\"ok\":false,\"error\":\"not_authed\"}",...
According to the Slack WebAPI docs, if I'm posting as the Bot, I should use the Bot's access token (as received from the initial oauth), but figure I'm either formatting my request incorrectly, or the token is not what Slack is expecting.
Ok, after talking with Slack support, it appears (at least) the WebAPIs I am calling don't yet support application/json. These do work with x-www-form-urlencoded.
Looking at this post
I was able to cobble together the following which auth'd successfully:
//up top
var request = require("request");
var querystring = require("querystring");
//...
app.get("/testAuth/test", function(req,res){
console.log("in testAuth/test...sending test message to Slack");
var bToken = process.env.TESTBOT_ACCESS_TOKEN;
var message = {
token: bToken
};
var messageString = querystring.stringify(message);
var messageLength = messageString.length;
var slackMessageURL = "https://slack.com/api/auth.test";
var postOptions = {
headers: {
"Content-length": messageLength,
"Content-type": "application/x-www-form-urlencoded"
},
uri: slackMessageURL,
body: messageString,
method: "POST"
};
request(postOptions, (error, response, body) => {
if(error){
console.log("OOPPPPS....we hit an error in auth.test: " + error);
} else {
console.log("auth.test response: " + JSON.stringify(response));
}
});
res.send("Sent Test...check logs");
});
I have tried 2 types of ajax calls to post json data so that i can order an item using woocommerce API. I am using OAuth1.0a to authorize the user. Its getting the data but not able to post the data. But none of them worked for me. So please somebody say how to post json data using ajax call. Thanks in advance.
var oauth2 = OAuth({
consumer: {
public: 'key',
secret: 'secret'
},
signature_method: 'HMAC-SHA1'
});
var token = {
public: 'key',
secret: 'secret'
};
var dataToSend = {};
var request_data = {
url: 'http://www.example.com/wc-api/v3/orders',
method: 'POST',
data: dataToSend
};
return $.ajax({
url: request_data.url,
type: request_data.method,
data: oauth2.authorize(request_data, token)
});
return $.ajax({
url: request_data.url,
type: request_data.method,
'content-type': 'application/json',
body: request_data.data,
headers: oauth2.toHeader(oauth2.authorize(request_data, token))
});
dataToSend - Example Data
key is genetrated using below link :
https://docs.woothemes.com/document/woocommerce-rest-api/
Just simply see all the headers in the oauth2.authorize(request_data, token)
and simply add all those headers to the url after '?'...That's the solution i had...
var generatedoauth = oauth.authorize(request_data, token);
console.log("oauth " + JSON.stringify(generatedoauth));
var newUrl = '<Url Goes Here>';
var paramsSt = '?oauth_consumer_key=' + generatedoauth.oauth_consumer_key + '&oauth_nonce=' + generatedoauth.oauth_nonce + '&oauth_signature_method=' + generatedoauth.oauth_signature_method + '&oauth_timestamp=' + generatedoauth.oauth_timestamp + '&oauth_signature=' + generatedoauth.oauth_signature;
newUrl = newUrl + paramsSt;`
environment:
-> Front-end: jquery that randle ajax request
-> Back-end: nodejs, expressjs (v.3.4.8).
I trying to create a simple contact form.
my front-end code:
var nome = $('#nome').val();
var email = $('#email').val();
var assunto = $('#assunto').val();
var mensagem = $('#mensagem').val();
var info = {'nome':nome, 'email':email, 'assunto':assunto, 'mensagem':mensagem};
$.ajax({
type: "POST",
url: "/contact",
data: { info: JSON.stringify(info) }
}).done(function(retorno){
//do something important
});
this work fine, i tested and on firebug everything from front-end is ok.
but i dont know how to deal with express that need read json from post request.
I just have it:
app.post('/contact', function(req, res){
});
The problem is in:
var info = {'nome':nome, 'email':email, 'assunto':assunto, 'mensagem':mensagem};
Just change the JSON ' ' to " " and works fine. I came from php and php recognize both ' ' and " " on a JSON, but nodejs just recognize strictly " ".
After some coding the result for a simple example of contact form is:
In a file common.js (front-end):
var nome = $('#nome').val();
var email = $('#email').val();
var assunto = $('#assunto').val();
var mensagem = $('#mensagem').val();
var info = {"nome":nome, "email":email, "assunto":assunto, "mensagem":mensagem};
$.ajax({
type: "POST",
url: "/contact",
data: JSON.stringify(info),
contentType:"application/json; charset=utf-8",
dataType: 'json'
}).done(function(retorno){
//do something at the end
}
In a file app.js or server.js or anything else (back-end):
var http = require("http")
, express = require('express')
, nodemailer = require('nodemailer')
, app = express();
app.use(express.json());
app.use(express.static(__dirname+'/public'));
app.post('/contact', function(req, res){
var name = req.body.nome;
var email = req.body.email;
var subject = req.body.assunto;
var message = req.body.mensagem;
var mailOpts, smtpTrans;
smtpTrans = nodemailer.createTransport('SMTP', {
service: 'Gmail',
auth: {
user: "your.user#gmail.com",
pass: "your.password"
}
});
mailOpts = {
from: name + ' <' + email + '>', //grab form data from the request body object
to: 'recipe.email#gmail.com',
subject: subject,
text: message
};
smtpTrans.sendMail(mailOpts, function (error, response) {
//Email not sent
if (error) {
res.send(false);
}
//Yay!! Email sent
else {
res.send(true);
}
});
});
app.listen(80, '127.0.0.2');
From this example: http://blog.ragingflame.co.za/2012/6/28/simple-form-handling-with-express-and-nodemailer
I have a HTML form for filling the personal profile, which includes String and Images. And I need to post all these data as JsonObject with one backend api call, and the backend requires the image file sent as binary data. Here is my Json Data as follow:
var profile = {
"userId" : email_Id,
"profile.name" : "TML David",
"profile.profilePicture" : profilePhotoData,
"profile.galleryImageOne" : profileGalleryImage1Data,
"profile.referenceQuote" : "Reference Quote"
};
and, profilePhotoData, profileGalleryImage1Data, profileGalleryImage2Data, profileGalleryImage3Data are all image Binary data(Base64).
And here is my post function:
function APICallCreateProfile(profile){
var requestUrl = BASE_URL + API_URL_CREAT_PROFILE;
$.ajax({
url: requestUrl,
type: 'POST',
data: profile,
dataType:DATA_TYPE,
contentType: CONTENT_TYPE_MEDIA,
cache:false,
processData:false,
timeabout:API_CALL_TIMEOUTS,
success: function (response) {
console.log("response " + JSON.stringify(response));
var success = response.success;
var objectData = response.data;
if(success){
alert('CreateProfile Success!\n' + JSON.stringify(objectData));
}else{
alert('CreateProfile Faild!\n'+ data.text);
}
},
error: function(data){
console.log( "error" +JSON.stringify(data));
},
failure:APIDefaultErrorHandler
})
.done(function() { console.log( "second success" ); })
.always(function() { console.log( "complete" ); });
return false;
}
But still got failed, I checked the server side, and it complains about the "no multipart boundary was found".
Can anyone help me with this, thanks:)
Updates:
var DATA_TYPE = "json";
var CONTENT_TYPE_MEDIA = "multipart/form-data";
I think I found the solution with vineet help. I am using XMLHttpRequest, and didn't set the requestHeader, but it works, very strange. But hope this following can help
function APICallCreateProfile(formData){
var requestUrl = BASE_URL + API_URL_CREAT_PROFILE;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange=function()
{
if (xhr.readyState==4 && xhr.status==200){
console.log( "profile:" + xhr.responseText);
}else if (xhr.readyState==500){
console.log( "error:" + xhr.responseText);
}
}
xhr.open('POST', requestUrl, true);
// xhr.setRequestHeader("Content-Type","multipart/form-data; boundary=----WebKitFormBoundarynA5hzSDsRj7UJtNa");
xhr.send(formData);
return false;
}
Why to reinvent the wheel. Just use Jquery Form Plugin, here. It has example for multipart upload as well.
You just need to set input type as file. You will receive files as input stream at server (off course they will be multipart)