PUT requests with CORS-anywhere [closed] - proxy

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am using cors-anywhere as a proxy server of sorts to overcome some cors problems I was having. My project only requires GET and PUT requests. cors-anywhere solved all my cors and GET problems but now with PUT I am getting 500 error. Below is how I set up my server and make the PUT request:
//setting up server
var host = process.env.HOST || '0.0.0.0';
var cors_proxy = require('cors-anywhere');
cors_proxy.createServer({
originWhitelist: [], // Allow all origins
removeHeaders: ['cookie', 'cookie2']
}).listen(8000, host, function() {
console.log('Running CORS Anywhere on ' + host + ':' + 8000);
});
//making call
let result = await fetch(`http://localhost:8000/${apiUrl}`, {
method: 'PUT",
mode: 'cors',
body: JSON.stringify({"value":"true"})
});
let json = await result.json();
console.log(json);
Everything here works with GET requests and gives a 500 error with PUT request when done through my TypeScript and JavaScript projects. If I use Postman with the same URLs, everything works perfectly. Any ideas on what is going on?
Thank you for your help.

Just figured out the problem. I wasn't declaring the content type in the PUT fetch request header. Correct one looks like this:
let result = await fetch(`http://localhost:8000/${apiUrl}`, {
method: 'PUT",
mode: 'cors',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({"value":"true"})
});

Related

Token destroy with djoser

I'am using django and trying to destroy a token when user log out, this is the function I'am using :
const logMeOut = async () => {
setAnchorEl(null);
const response = await fetch('http://127.0.0.1:8000/api-auth/token/logout/', {
method: 'POST',
headers: {
'Authorization': 'Token '.concat(GlobalState.userToken),
'Content-Type': 'application/json',
},
})};
However my server is throwing :
POST http://127.0.0.1:8000/api-auth/token/logout/ 401 (Unauthorized)
What I'am I doing wrong ? I know it's something about the headers or something like that... but I have been switching headers and nothing changes.
Okay, I found out what the problem was and I'll leave it here for anyone who might be facing the same issue.
In my particular case, I was getting unauthorized because I send the same token multiple times and the token was destroyed the first time I sent the request to the backend...
Basically, I didn't destroy the token in the frontend and kept sending the same token which was already destroyed, which means there is nothing wrong with the piece of code above and it should work.

Does Micorsoft teams require special provisioning to improve rate limiting issues?

We are hitting rate limiting issues with Graph APIs usage. Is there any way to upgrade our tenant/membership to improve the performance and response times?
It takes up to minutes, and sometimes APIs not getting processed at all. We require real time response.
Any pointers in this regard will be really helpful.
Thanks
Laksh
Request Type : Get Channel messages API using Global Admin credentials is called with 1Second interval
Request URL : GET https://graph.microsoft.com/beta/teams/${teamId}/channels/${channelId}/messages
const options = {
headers: {
Authorization: `Bearer ${globalAdminAccessToken}`,
‘Content-Type': 'application/json',
Accept: '*/*'
}
};
let url = `https://graph.microsoft.com/beta/teams/${teamId}/channels/${channelId}/messages`;
axios
.get(
url,
options
)
.then(resp => {
console.log(resp);
})
.catch(error => {
console.log(error);
});

how to prevent internet explorer from caching ajax request in angular2, typescript?

Scenario is that user have some points lets say 10 pts. so after clicking on button an ajax get call sent to server that update the points of user as he/she consumed it. So, server should send 9 which is working on all browsers except Internet Explorer. After searching I found that IE not even making the request it is caching that request. How to solve this issue ?
Thanx in advance !
If you have control on the server code, you should set the appropriate headers that disallow caching.
You can set the headers
Cache-Control: no-cache
Expires: -1
A possible approach would be to implement an HTTP interceptor and append a timestamp if the request with the URL has already been executed.
#Injectable()
export class CustomHttp extends Http {
urls: {string:string} = {};
get(url: string, options?: RequestOptionsArgs): Observable<Response> {
if (this.urls[url]) {
options = options || {};
options.search = options.search || new URLSearchParams();
options.search.set('timestamp', (new Date()).getTime());
}
return super.get(url, options).do(() => {
this.urls[url] = true;
});
}
}

POST REFUND returned error 400 since Feb ~10th [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have a script processing some refund payments that does not work anymore since approx. Feb 10th. Server responds Content-Type is not supported ... even if my header Content-Type looks actually correct
Same code worked before that date which makes me believe something was changed on the server side but I haven't notice anything in the square-connect API changelog recently that would explain this problem.
Any help would be much appreciated :)
Thanks
See below JSON request and response.
{"method":"POST",
"headers":
{"Authorization":"Bearer [mypersonalid]",
"Accept":"application/json",
"Content-Type":"application/json"},
"payload":
{"payment_id":"[paymentid]",
"type":"FULL",
"reason":"reason"
}
}"
}
{"type":"bad_request",
"message":"The Content-Type of this request is not supported.
Supported type(s): application/json"
}
Since you're using Google App Script, it looks like you have to set the Content-Type header using the special contentType parameter (docs here). That way, Google Apps Script knows to serialize the payload as JSON rather than multipart form data. If you just specify it as a header, Google will override it.
Thanks a lot your comments. It's solved!
I've added the contentType in the params and it did not worked but I started to get a new error saying 'bad json object'. Si, I just searched for that and found that the actual encoding of the 'payload' object needed to be "stringify". See answer from user1021710 : https://stackoverflow.com/a/18851043/4615977 ("Google Apps Script UrlFetchApp with JSON Payload")
So in this case, contentType was necessary then encoding of the payload too. Google changed their own API around mid-Feb apparently, because code was the same and worked.
Thanks folks !!!
Sample basic code to POST refund request using google app script:
var headers = {
"Authorization" : autorization,
"Accept": 'application/json',
"Content-Type": "application/json",
};
var payload = {
"payment_id" : paymentid,
"type" : type,
"reason" : reason,
};
var params = {
"contentType": "application/json",
"headers" : headers,
"method" : "post",
"payload" : JSON.stringify(payload),
};
var url = "https://connect.squareup.com/v1/me/refunds";
paymentsFetch = UrlFetchApp.fetch(url, params);

Ajax calls from node to django

I'm developing a django system and I need to create a chat service that was in real-time. For that I used node.js and socket.io.
In order to get some information from django to node I made some ajax calls that worked very nice when every address was localhost, but now that I have deployed the system to webfaction I started to get some errors.
The djando server is on a url like this: example.com and the node server is on chat.example.com. When I make a ajax get call to django I get this error on the browser:
XMLHttpRequest cannot load http://chat.example.com/socket.io/?EIO=3&transport=polling&t=1419374305014-4. Origin http://example.com is not allowed by Access-Control-Allow-Origin.
Probably I misunderstood some concept but I'm having a hard time figuring out which one.
The snippet where I think the problem is, is this one:
socket.on('id_change', function(eu){
sessionid = data['sessionid']
var options = {
host: 'http://www.example.com',
path: '/get_username/',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': sessionid.length
}
}
var request = http.request(options, function(response) {
response.on('data', function(msg){
console.log('Received something')
if(response.statusCode == 200){
//do something here
}
}
})
})
request.write(sessionid);
request.end();
});
And I managed to serve socket.io.js and make connections to the node server, so this part of the setup is ok.
Thank you very much!
You're bumping into the cross origin resource sharing problem. See this post for more information: How does Access-Control-Allow-Origin header work?
I am NOT a Django coder at all, but from this reference page (https://docs.djangoproject.com/en/1.7/ref/request-response/#setting-header-fields) it looks like you need to do something like this in the appropriate place where you generate responses:
response = HttpResponse()
response['Access-Control-Allow-Origin'] = 'http://chat.example.com'

Resources