I've been trying to connect to MailChimp 3.0 API through the JS function below:
var mailchimp_api_key = (api key as in my account);
var name = $('#name').val();
var email = $('#email').val();
if(name.indexOf(' ') != 0) {
var fname = name.substr(0, name.indexOf(' '));
var lname = name.substr(name.indexOf(' ') + 1);
} else {
fname = name;
}
var mailchimp = JSON.stringify({
email_address: email,
status: 'subscribed',
merge_fields: {
FNAME: fname,
LNAME: lname
}
});
$.ajax({
url: 'http://(my server in MC).api.mailchimp.com/3.0/lists/(list id)/members/',
type: 'POST',
data: mailchimp,
dataType: 'jsonp',
contentType: 'application/json; charset=utf-8',
error: function(res, text){
console.log('Err', res);
},
success: function(res){
console.log('Success', res);
},
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa("api:" + mailchimp_api_key))
}
});
My problem is that I've been getting an 401 error, and nothing I do correct this.
I'm local and not using a server.
Related
I want to send some attributes and a file to a Node JS application with multipart/form-data.
Client HTML Form:
<input id="picName" name="picName" class="form-control" placeholder="PicTitle..." style="border-radius: 1%; margin: 1%" type="name">
<form id="frmUploader" enctype="multipart/form-data" action="/post/picture/" method="post">
<input id="file" type="file" name="picUploader" multiple /><br>
<input class="btn btn-md btn-success" type="submit" name="submit" id="btnSubmit" value="Upload" /><br>
</form>
Client JS:
$('#frmUploader').submit(function () {
var username = localStorage.getItem("userName");
var categoryName = $( "#categoryAddPic option:selected").text();
var picTitle = $('#picName').val();
var picture = $('input[name="picUploader"]').get(0).files[0];
var formData = new FormData();
formData.append('picture', picture);
formData.append('username', username);
formData.append('categoryName', categoryName);
formData.append('picTitle', picTitle);
$.ajax({
method: 'POST',
url: 'http://localhost:3000/post/picture',
data: formData,
headers:{
"Authorization": "bearer " + token
},success:function (respond) {
...
});
}
return false;
});
Now I want to save the data of the form in my Node application. If it is necessary to know too, I´m using multer for saving the file on the server.
Thanks for help.
PS: The node version is 4.8.3
Node JS:
app.post('/post/picture',function (req, res, next) {
var picName = req.body.picName;
var username = req.body.username;
var displayPic = req.body.displayPic;
var createdAt = moment();
var updatedAt = moment();
var categoryName = req.body.categoryName;
var picIdForCat = null;
try {
if (username) {
upload(req, res, function (err) {
if (err) {
return res.end("Something went wrong!");
}
//return res.end("File uploaded sucessfully!.");
picName = pictureSaveFormat;
var pictureCont = "./pictures/" + picName + ".jpg";
User.findOne({
where: {username: username}
}).then(function (user) {
var picture = {
picName: picName,
picture: pictureCont,
displayPic: null,
createdAt: createdAt,
updatedAt: updatedAt,
UserIdUser: user.idUser
};
Pictures.create(picture);
if (categoryName) {
Pictures.findOne({
where: {picName: picture.picName}
}).then(function (pic) {
picIdForCat = pic.idPic;
Category.findOne({
where: {categoryName: categoryName}
}).then(function (category) {
var catId = category.idCat;
var catForPic = {PictureIdPic: picIdForCat, CategoryIdCat: catId};
CategorieForPic.create(catForPic);
//res.redirect('localhost:3000/index.Admin.html');
res.status(200).json({message: "Picture from: " + username + " with name: " + picName + " created with " + category.categoryName + "."});
})
}).catch(function (req, res, err) {
res.status(500).json({message: "Error: Adding Category to pic", reason: err});
});
} else {
//res.redirect('localhost:3000/index.Admin.html');
res.status(200).json({message: "Picture from: " + username + " with name: " + picName + " created without a category."});
}
}).catch(next);
});
} else {
res.status(404).json({message: "Not found.", reason: "A required parameter is missing."});
}
}catch (err){
res.status(500).json({message: "Fatal Server error: ", reason: err});
}
});
When using a FormData object with jQuery.ajax, you have to set processData to false so that jQuery will not try to encode the FormData object and contentType to false so that jQuery will not set any content type headers. When FormData is used with ajax the proper content type header is generated for you.
$.ajax({
method: 'POST',
url: 'http://localhost:3000/post/picture',
data: formData,
processData: false,
contentType: false,
headers:{
"Authorization": "bearer " + token
},
success:function (respond) {
...
});
}
headers: {
"Content-Type": "multipart/form-data",
"Authorization": "bearer " + token
},
It was working on my side
I've been experimenting with creating an AngularJS service that can be called from the controller and send text messages based on particular events in the application. The implementation is based on this, and works as follows:
Firstly, we have the service:
function BusinessService($http) {
this.twilioSMS = {
sendMessage: function(to, from, body) {
var accountSid = 'xxx';
var authToken = 'xxx';
var testEndpoint = 'https://api.twilio.com/2010-04-01/Accounts/' + accountSid + '/SMS/Messages.json';
var liveEndpoint = 'https://api.twilio.com/2010-04-01/Accounts/' + accountSid + '/Messages.json';
var data = {
To: to,
From: from,
Body: body
};
$http({
method: 'POST',
url: testEndpoint,
data: data,
dataType: 'json',
contentType: 'application/x-www-form-urlencoded',
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization",
"Basic " + btoa(accountSid + ":" + authToken) // !
);
},
success: function(data) {
console.log("Got response: %o", data);
if (typeof successCallback == 'function')
successCallback(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Request failed: " + textStatus + ", " + errorThrown);
if (typeof failCallback == 'function')
failCallback(jqXHR, textStatus, errorThrown);
}
})
}
}
}
Then setting it up in the controller:
function ConsumerBusinessProfileCtrl($scope, BusinessService) {
$scope.sendMessage = function(to, from, body) {
return BusinessService.twilioSMS.sendMessage(to, from, body)
}
}
And then calling it from the view:
<a ng-click="sendMessage('+12345678901', '+15005550006', 'Hey Jenny! Good luck on the bar exam!')">Send Message</a>
I've tested the jsfiddle example with my accountSid, authToken, and phone numbers and it is working fine. But my implementation fails with a 401 (UNAUTHORIZED) error. A part of me thinks that this is because $http does not support beforeSend or afterSend. But I am not sure? Can anybody here guide me in the right direction?
Changed $http to the following to fix things:
$http({
method: 'POST',
url: testEndpoint,
data: data,
transformRequest: function(obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
headers: {
'Authorization': 'Basic ' + btoa(accountSid + ':' + authToken),
'Content-Type': 'application/x-www-form-urlencoded'
},
}).success(function(response) {
console.log(response);
}).error(function(error) {
console.log(error);
});
}
I am trying to post a video from the browser to an edge sing the below code
var url = "https://graph.facebook.com/v2.5/" + this.uid + "/videos" + "?access_token=" + token;
var formData = new FormData();
formData.append("source", file);
formData.append("access_token", token);
return $.ajax({
url: url,
contentType: false,
processData: false,
type : "POST",
data: formData
})
But it gives a 400 bad request error.The response is
{
"error": {
"message": "Bad signature",
"type": "OAuthException",
"code": 1,
"fbtrace_id": "FYc5192NtSs"
}
}
Can you please tell me what am I doing wrong ?
I made the following utility function
var makeApiRequest: function(accessToken, config, successCallback, errorCallback) {
var baseUrl = 'https://graph.facebook.com/v2.5/';
// parse config and defaults
var config = config || {},
url = config.url || 'me',
data = config.data || {},
method = config.method || 'GET';
config.url = baseUrl + url + '&access_token=' + accessToken;
// make the api request
$.ajax(config)
.done(function(data) {
if (!!successCallback) {
successCallback(data);
} else {
console.log(data);
}
}
).error(function(xhr) {
errorCallback(xhr);
});
}
Which can be called like this for a video.
makeApiRequest(
'<token>',
{
url: 'me/videos',
data: {file_url:'http://example.com/path/to/file.mp4', description: 'title'},
method: 'POST'
}, successCb, errorCb);
Please ensure you use a token which was acquired using v2.5 of the API. You need publish_actions, publish_pages (for pages) permission to post
Debug your access token here
I want to create ajax call with authorization headears only when user writes username and password. When this vars are empty I need to create ajax call without authorization headers. How can I do this? Can I make it with one ajax or I need to create two ajax every for one situation?
var username = "user123";
var password = "pass123";
//var username = "";
//var password = "";
$.ajax({
type: "GET",
url: url_survey,
dataType: "json",
headers: {
'Authorization': "Basic " + btoa(username + ":" + password)
},
success:
function (data) {
alert("SUCCESS");
},
error:
function (data) {
alert("ERROR");
}
});
Try this:
var username = "user123";
var password = "pass123";
//var username = "";
//var password = "";
var headers = {}; //list of headers
if(username && password) //user and pass exists
headers['Authorization'] = "Basic " + btoa(username + ":" + password);
$.ajax({
type: "GET",
url: url_survey,
dataType: "json",
headers: headers, //use our headers
success:
function (data) {
alert("SUCCESS");
},
error:
function (data) {
alert("ERROR");
}
});
The parameter passed to $.ajax is just an object. Just simply create it, add properties as needed, then send it to `$.ajax.
var ajaxData = {
type: "GET",
url: url_survey,
dataType: "json",
success:
function (data) {
alert("SUCCESS");
},
error:
function (data) {
alert("ERROR");
}
};
if(username && password){
ajaxData.headers = {
'Authorization': "Basic " + btoa(username + ":" + password)
};
}
$.ajax(ajaxData);
I have a RESTful web service (hosted on a different server via IIS) that returns JSON. The strange thing is the following NodeJS command line test application (not via the web browser, but via the command line) is working fine and returning the JSON:
Working NodeJS App:
var request = require("request");
var btoa = require("btoa");
var uname = "corp\\user.name";
var pword = "password123"
var options = {
url: "http://192.168.3.142/v1/foo?format=json",
headers: {
"Authorization": "Basic " + btoa(uname + ":" + pword)
}
};
request(options, function(err, response, body) {
console.log(body);
});
However the following AJAX request fails with:
OPTIONS http://192.168.3.142/v1/foo?format=json 401 (Unauthorized) jquery-1.11.0.min.js:4
XMLHttpRequest cannot load http://192.168.3.142/v1/foo?format=json. Invalid HTTP status code 401
This is the response header from the server:
Response Headers:
Access-Control-Allow-Headers:Authorization
Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin:*
Content-Length:1293
Content-Type:text/html
Date:Thu, 06 Mar 2014 05:41:24 GMT
Server:Microsoft-IIS/7.5
WWW-Authenticate:Basic realm="192.168.3.142"
X-Powered-By:ASP.NET
AJAX code:
$.ajaxSetup({
beforeSend: function (xhr, settings) {
var creds = {
username: "corp\\user.name",
password: "password123"
};
xhr.setRequestHeader("Authorization", "Basic " + btoa(creds.username + ":" + creds.password));
return true;
}
});
$.ajax({
type: "GET",
url: "http://192.168.3.142/v1/foo?format=json",
success: function (data, text) {
console.log(data);
}
});
UPDATE:
Throws the same 401 (Unauthorized):
var creds = {
username: "corp\\user.name",
password: "password123"
};
var credentials = btoa(creds.username + ":" + creds.password);
$.ajax({
type: "GET",
dataType: "text/json",
url: "http://192.168.3.142/v1/foo?format=json",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Basic " + credentials);
return true;
},
success: function (data, text) {
console.log(data);
}
});
Once I added xhrFields: { withCredentials: true } to the $.ajaxSetup({}); the error was returning:
Credentials flag is 'true', but the 'Access-Control-Allow-Credentials' header is ''. It must be 'true' to allow credentials.
I added Access-Control-Allow-Credentials: true on the server-side and it's now working correctly.
var creds = {
username: "username",
password: "password"
};
var credentials = btoa(creds.username + ":" + creds.password);
$.ajaxSetup({
xhrFields: { withCredentials: true },
beforeSend: function (xhr, settings) {
xhr.setRequestHeader("Authorization", "Basic " + credentials);
return true;
}
});
$.ajax({
type: "GET",
url: "http://localhost/v1/service",
async: true,
success: function (data, text) {
console.log(data);
}
});