Can't access Outlook REST API from within Outlook Add in - outlook

I have created an Outlook addin project using yo office command. Inside it I'm trying to fetch list of mails, using the below code:
// Get access token
Office.context.mailbox.getCallbackTokenAsync({isRest: true}, function(result){
if (result.status === "succeeded") {
var accessToken = result.value;
console.log('Access token : ' + accessToken);
} else {
console.log('Unable to get access token :(');
}
// Get item id
var itemId = Office.context.mailbox.convertToRestId(
Office.context.mailbox.item.itemId,
Office.MailboxEnums.RestVersion.v2_0
);
console.log('Item Id : ' + itemId);
// Get messages now
var messagesUrl = Office.context.mailbox.restUrl + 'v2.0/me/messages/' + itemId;
console.log('Querying url : ' + messagesUrl);
$.ajax({
url: messagesUrl,
dataType: 'json',
headers: { 'Authorization': 'Bearer ' + accessToken }
}).done(function(item){
console.log(item);
}).fail(function(error){
console.log(error);
});
});
The problem is that on running the addin, I get the following error:
SEC7120: Origin https://localhost:3000 not found in Access-Control-Allow-Origin header.
SCRIPT7002: XMLHttpRequest: Network Error 0x80070005, Access is denied.
Any help would be appreciated. The permission set in the manifest file is <Permissions>ReadWriteMailbox</Permissions>

Verify that you have CORS enabled on the server:
Access-Control-Allow-Origin: *
See https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS for more details.

Related

Authorization failed on a fetch request to the Brawl Stars API

I'm trying to send a get request with fetch API to ask the brawl stars API server. I've created an API KEY associated with my IP address. I've tried everything, but I got a 403 response from the server.
Here is my code :
const url = 'https://api.brawlstars.com/v1/players/...';
const token = '...';
const headers = new Headers({
'Accept': 'application/json',
'Authorization': 'Bearer ' + token
});
const options = {
method: 'GET',
headers: headers,
mode: 'cors',
cache: 'default'
};
fetch(url, options)
.then(response => response.json())
.then(console.log)
.catch(console.error);
In the console there is the message : No 'Access-Control-Allow-Origin' header is present on the requested resource because of cors policy.
When I test the request on Insomnia, it works well !
I had a problem with the Brawlstars API a little while back when I was making a Brawlstars command for my Discord bot. I was able to get the API to work however with the following code.
const playerurl = 'https://api.brawlstars.com/v1/players/';
const getJSON = async url => {
try {
const response = await fetch(url, {
method: 'GET',
headers: {
Accept: 'application/json',
Authorization: 'Bearer <yourapitoken>',
},
});
if(!response.ok) {throw new Error(response.statusText);}
const data = await response.json();
return data;
}
catch(error) {
return error;
}
};
getJSON(playerurl).then(data => {
console.log(data);
}).catch(error => {
console.error(error);
});
I hope this works for you!

Call IIS published web api using ajax call issue with CORS policy

I developed a sample web application using normal(.aspx) page on the client button click following function I written for the web API call
function AddEmp() {
var Emp = {};
Emp.FirstName = $("#txtFirstName").val();
Emp.LastName = $("#txtLastName").val();
Emp.Company = $("#txtCompany").val();
$.ajax({
url: 'http://localhost:55339/api/Emp/AddEmployees',
type: 'POST',
contentType: 'application/json;charset=utf-8',
data: JSON.stringify(Emp),
dataType: 'json',
success: function (response) {
alert(response);
},
error: function (x, e) {
}
});
}
In the web API, Emp controller following function code is written for insert into the data base.
public string AddEmployees(Employee Emp)
{
connection();
com = new SqlCommand("InsertData", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#FName", Emp.FirstName);
com.Parameters.AddWithValue("#Lname", Emp.LastName);
com.Parameters.AddWithValue("#Compnay", Emp.Company);
con.Open();
int i = com.ExecuteNonQuery();
con.Close();
}
on button click, I receive following error in the inspector
Access to XMLHttpRequest at 'http://localhost:55339/api/Emp/AddEmployees' from origin 'http://localhost:2252'
has been blocked by CORS policy: Response to preflight request doesn't pass access control
check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I have tried the following option
crossDomain: true,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
Nothing will work. How to resolve this issue.

How do I get Postman to call my Web API

I'm got the pluggin Postman for Chrome. I'm just wondering how I would get Postman to call my web API.
Current, I'm using this AJAX call written in Javascript:
alert("Getting security token");
// Do AJAX call to get security token:
$.ajax({
url: [security token url],
type: "POST",
headers: {
Accept: "application/json"
},
ContentType: "application/x-www-form-urlencoded",
data: {
grant_type: "password",
username: [username],
password: [password]
}
}).done(function(data)
{
var accessToken = data.access_token;
alert(accessToken);
alert("Getting json string.");
// Now that we have access token, send it along with the request for the json string:
$.ajax({
// meta data sent as URL parameters:
url: [url to get json string]
type: "GET",
headers: {
Authorization: "Bearer " + accessToken // access token
},
contentType: false,
processData: false
}).done(function(data)
{
$("#jsonDiv").html(data);
}).fail(function(jqXhr, textStatus, errorThrown)
{
alert("jqXhr = " + JSON.stringify(jqXhr));
alert("textStatus = " + textStatus + ", errorThrown = " + errorThrown);
});
}).fail(function(jqXhr, textStatus, errorThrown)
{
alert("jqXhr = " + JSON.stringify(jqXhr));
alert("textStatus = " + textStatus + ", errorThrown = " + errorThrown);
});
What would I have to do in Postman to accomplish the equivalent of this?
Thanks
There are a few ways to achieve this, but here are some steps to get you started. Create two 2 APIs:
The first to call the "security token url" with the POST method.
Add the header:
Accept: application/json
Then under body, select x-www-form-urlencoded and then add the following keys (and their appropriate values):
grant_type : password
username :
password :
Off the top of my head I think the password grant_type also requires client_id and client_secret, but I don't see that in your code above so maybe you don't need it.
If you hit send you should get an access token back.
In your second API, set the method to GET and supply the appropriate URL. Then in the headers add:
- Authorization : Bearer
If you want to get fancy you can use the test tab to write the access token to an environment variable and then use the result in your second call.
You don't need to get a new access token for each call however so you can just keep using the same token until it expires.
Sorry if you already knew how to do this, I couldn't tell your level of expertise from your question. Hope this helps.

Access-Control-Allow-Origin' header is present on the requested resource. error

My ajax call is as follows
var data = {};
data.name = name;
data.phone = phone;
data.address=address;
$.ajax({
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json',
url: 'http://localhost:5000/endpoint',
success: function(data) {
console.log('success');
console.log(JSON.stringify(data));
}
});
and I am using node-js express server
and my server code is
app.post('/endpoint', function(req, res){
var obj = {};
console.log('body: ' + JSON.stringify(req.body));
res.send(req.body);
});
app.listen(5000);
I have tried the other solutions posted but I still keep getting this error
Response to preflight request doesn't pass access control check: No Access-Control-Allow-Origin header is present on the requested resource. Origin http://localhost:3000 is therefore not allowed access.
What do I need to do ?
Before your routing on your server, add :
app.all('/*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
});
You can replace the * with the URL of authorized domains.
More informations : https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

CORS is driving me crazy - intermittent issues

It seems like I've tried everything and I finally just switched to using the CORS npm module:
var cors = require('cors');
And my one route I want to use CORS on:
app.post('/hangouts', cors(), hangoutsController.hangouts); // user CORS
I'm implementing a custom app in Google Hangouts, but need to post to my server, and the Hangout is run from a Google server. I put the AJAX call on a loop so that it will keep trying - this post going through is crucial to my app.
Here's the relevant AJAX call in the Hangout app:
var shouldpostHangoutId = true;
/* Post the Hangout ID to server */
var postHangoutId = function(hangoutId) {
var startData = gapi.hangout.getStartData();
$.ajax({
type: 'POST',
url: rootURL + "/hangouts",
crossDomain: true,
dataType: "json",
data: {
"hangouts_id" : hangoutId,
"start_data" : startData
},
success: function( response ) {
console.log( "postHangoutId -- success" ); // server response
console.log( response ); // server response
shouldpostHangoutId = false;
},
error: function(xhr, textStatus, error){
console.log( "postHangoutId -- error" ); // server response
console.log(xhr.statusText);
console.log(textStatus);
console.log("error = " + error);
// Try again
if (shouldpostHangoutId) {
postHangoutId(hangoutId); // Try again
};
}
});
};
What's driving me crazy is that sometimes it goes through on the first go, sometimes it takes 5 times. And the whole process is super slow. Here's the log I get when it doesn't come through:
XMLHttpRequest cannot load https://www.foo.bar/hangouts. No 'Access-Control-Allow-Origin' header
is present on the requested resource. Origin 'https://ts6d5n5om59gt6cin9c39faccjf890k5-a-hangout-
opensocial.googleusercontent.com' is therefore not allowed access.
I'm using Node + Express ~4 on Heroku.
I think the problem had something to do with pre-flight requests. I changed the AJAX call to the following:
$.ajax({
type: 'POST',
url: rootURL + "/hangouts",
dataType: "json",
data: {
"hangouts_id" : hangoutId,
"start_data" : startData
},
error: function( error ){
// Log any error.
console.log( "ERROR:", error );
// Try again
if (shouldpostHangoutId) {
postHangoutId(hangoutId); // Try again
};
},
complete: function(){
console.log( "postHangoutId -- success" ); // server response
shouldpostHangoutId = false;
}
});
And it goes right through, first time without delay.

Resources