问题
Hi I would like to Create JavaScript app which post message to Yammer, using Yammer REST API. but I have a limitation. I Can Not use Yammer SDK to post message. so, I written code of ajax.
However, In this code Doesn't work. XMLHTTPrequest is always "access denied".
why this code doesn't work?
MY Yammer network allow 3rd party app.
function sendData() {
var messagebody = new Object();
messagebody.body = "This is test";
messagebody.group_id ="4627253"
//get accToken
accToken = responseObject.access_token.token;
var accAuthHead = "Bearer "+ accToken;
$.ajax({
url: "https://www.yammer.com/api/v1/messages.json",
type: 'POST',
headers: {
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Accept-Encoding': 'gzip, deflate',
'Authorization': accAuthHead.toString(),
'X-Requested-With': 'XMLHttpRequest',
},
data: JSON.stringify(messagebody),
datatype: "json",
success: function (data) {
console.log("ajax post success.");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("There was an error with the request." + textStatus.toString()+ XMLHttpRequest.toString());
}
});
}
回答1:
I've tried your code and found two serious issues that might cause your problems:
You should use https://api.yammer.com/api/v1/messages.json instead of https://www.yammer.com/api/v1/messages.json
Don't JSON.stringify your data as it's supposed to be sent as just that, JSON, not as a string.
Hope it helps!
回答2:
Thaks, Juan and Mark. I changed my code in your advice. and code working now. That is here.
function sendData(msgbody) {
//var messagebody = new FormData();
var testMessage = {
body: msgbody,
group_id: 4627253
}
var jsonObj = JSON.stringify(testMessage);
accToken = responseObject.access_token.token;
var accAuthHead = 'Bearer '+ accToken;
$.ajax({
url: "https://api.yammer.com/api/v1/messages.json",
type: 'POST',
headers: {
'Authorization': accAuthHead.toString(),
},
data: testMessage,
success: function (data) {
alert("ajax post success.");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("There was an error with the request." + textStatus + XMLHttpRequest.toString());
}
});
}
but It is a little funny. firstly, I tryed testing this code in "Internet Explorer 10". it did Not work. secondly, I use Chrome(versio 39.0.2171.95 m), it was worked!
I am little confused. Why I get this result?
来源:https://stackoverflow.com/questions/27596180/i-can-not-post-yammer-via-rest-api-using-ajax