Setting custom HTTP headers for dojox.io.script.get - javascript

I have Javascript app using dojox.io.script.get to make a GET request to a data-provider domain, which is different from the domain I'm issuing the request from (therefore I am relying on JSONP). I need to issue the HTTP request along with a custom header (myHeader).
Here's my code:
var args = {
url: 'http://datadomain/path/to/data?f=json',
callbackParamName: "handleData",
headers: { #
"myHeader": 'blablabla' # <-- DOESN'T SEEM TO WORK...
}, #
error: function(error){
//handle error
}
};
dojo.io.script.get(args);
function handleData(data){
//do something with "data"
}
I tested my code out but I got an error code from the server complaining about the fact that the information that should have been in the custom header is currently missing.
I read the dojox.io.script.get docs) but unfortunately no light shone on me...
Now, probably it's just me missing something or misunderstanding the JSONP workflow, but then how could I perform a cross-domain data request with HTTP custom headers?
Is it definitely possible to accomplish that using the dojo framework?
Thanks in advance!

Related

FastAPI rejecting POST request from javascript code but not from a 3rd party request application (insomnia)

When I use insomnia to send a post request I get a 200 code and everything works just fine, but when I send a fetch request through javascript, I get a 405 'method not allowed error', even though I've allowed post requests from the server side.
(Server side code uses python).
Server side code
from pydantic import BaseModel
from typing import Optional
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
origins = ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["POST", "GET"],
allow_headers=["*"],
)
class data_format(BaseModel):
comment_id : int
username : str
comment_body : Optional[str] = None
#app.post('/post/submit_post')
async def sumbit_post(somename_3: data_format):
comment_id = somename_3.comment_id
username = somename_3.username
comment_body = somename_3.comment_body
# add_table_data(comment_id, username, comment_body) //Unrelated code
return {
'Response': 'Submission received',
'Data' : somename_3
}
JS code
var payload = {
"comment_id" : 4,
"username" : "user4",
"comment_body": "comment_4"
};
fetch("/post/submit_post",
{
method: "POST",
body: JSON.stringify(payload),
headers: {
'Content-Type': 'application/json'
}
})
.then(function(res){ return res.json(); })
.then(function(data){ alert( JSON.stringify( data ) ) })
The error
What should I do to get around this error?
Thanks in advance.
To start with, your code seems to be working just fine. The only part that had to be changed during testing it (locally) was the URL in fetch from /post/submit_post to (for instance) http://127.0.0.1:8000/post/submit_post, but I am assuming you already changed that using the domain name pointing to your app.
The 405 Method Not Allowed status code is not related to CORS. If POST was not included in the allow_methods list, the response status code would be 400 Bad Request (you could try removing it from the list to test it). From the reference above:
The HyperText Transfer Protocol (HTTP) 405 Method Not Allowed response
status code indicates that the server knows the request method, but
the target resource doesn't support this method.
The server must generate an Allow header field in a 405 status code
response. The field must contain a list of methods that the target
resource currently supports.
Thus, the 405 status code indicates that the POST request has been received and recognised by the server, but the server has rejected that specific HTTP method for that particular endpoint. Therefore, I would suggest you make sure that the decorator of the endpoint in the version you are running is defined as #app.post, as well as there is no other endpoint with the same path using #app.get. Additionally, make sure there is no any unintentional redirect happening inside the endpoint, as that would be another possible cause of that response status code. For future reference, when redirecting from a POST to GET request, the response status code has to change to 303, as shown here. Also, you could try allowing all HTTP methods with the wildcard * (i.e., allow_methods=['*']) and see how that works (even though it shouldn't be related to that). Lastly, this could also be related to the configurations of the hosting service you are running the application; thus, might be good to have a look into that as well.
It's and old issue, described here. You need Access-Control-Request-Method: POST header in your request.

CORS enabled on AWS API, but still getting "No Access-Control-Allow-Origin" in Angular

I recently restructured my API on AWS Gateway to make all my Lambda functions use proxy integration - before that, every single parameter was passed in as a path parameter (awful, I know.)
I never had any issues with CORS then, and I've tried several things over the past few hours to fix the issue discussed in the topic line.
First, I used a proxy resource and used an "ANY" method, but when that gave me CORS issues, I enabled CORS on the API method and tried again - still nothing. So, I tried changing it so that it was a "POST" request instead and enabling CORS - still nothing. And I made sure to deploy after every setting change. Then, I got rid of the proxy and instead just made a "POST" method with CORS enabled, and still nothing.
I'm using Angular's http post method.
Edit:
I'm using Angular 1.6.4, and this is the code I'm using to call the API:
this.checkRegistered = function(email){
var data = { Email : email};
var toSend = JSON.stringify(data);
return $http.post('link', toSend);
};
That's in my service for the angular module, and it's being called from this function in the controller:
function CheckIsRegistered(email)
{
return userService.checkRegistered(email).then(function(res){
if (res.data.statusCode === 200){
return res.data.body;
}});
}
I've configured all the parameters so that "Email" is what it should be expecting, and I did replace the word 'link' with the actual link.
When I enable CORS through the console, I assign the headers as follows:
Access-Control-Allow-Headers: 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'
Access-Control-Allow-Origin: '*'
This is especially infuriating because I've actually worked with this exact issue before and solved it fairly easily, but now that I'm using Lambda's proxy integration I've run into this issue again and I can't quite seem to figure it out.
Any help is appreciated.
I figured out the problem - I had to add the headers for CORS to the Lambda response. Here's the code snippet for anyone else having similar problems:
connection.query('arbitrary query', [params], function (error, results, field) {
if (!error)
{
connection.end();
var responseBody = results;
response = { statusCode: 200,
headers: { "Access-Control-Allow-Headers": "Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token", "Access-Control-Allow-Origin": "*"},
body: JSON.stringify(responseBody)};
callback(null, response);
}
I put the querying line in there just for context of what "response" is.

CKEditor change in ajax URL ?t=timestam to ?open&t=timestamp

I use the CKEDITOR on my HTML page, but I can not connect it properly, my WEB server does not understand such requests and I need to change them.
My WEB server does not support requests like ?t=timestamp.
How can I change this, for example, to have ?Open&t=timestamp.
I have the following requests:
GET http://mysite.ru/webadmin/ckeditor/config.js?t=H4PG 400 (Bad Request)
GET http://mysite.ru/webadmin/ckeditor/skins/moono-lisa/editor.css?t=H4PG (Bad Request)
GET http://mysite.ru/webadmin/ckeditor/lang/ru.js?t=H4PG 400 (Bad Request)
Should be so
GET http://mysite.ru/webadmin/ckeditor/config.js?open&t=H4PG
GET http://mysite.ru/webadmin/ckeditor/skins/moono-lisa/editor.css?open&t=H4PG
GET http://mysite.ru/webadmin/ckeditor/lang/ru.js?open&t=H4PG
How to set my suffix for all connected plug-ins?
It seems to me that there is some parameter that will allow you to insert your HTTP command after the question.
Example,
CKEDITOR.config.<param>="open&"
or callback function
function(request){
request+="open&";
}
How to do it?
Tried it like this
function CKEDITOR_GETURL( resource ){
var base="/webadmin/ckeditor/";
var r=resource;
if(!/^\//.test(r))r=base+r;
return r;
}
But some of the resources are not properly processed, a bad idea

AngularJS $http.post() firing get request instead of post

i building an API service in angular and laravel, when i firing a GET call to the API everythings work fine, but when i fire POST call the service still use GET method instead of POST.
that is my service:
function LeadsAPI($http,$q,BASE_URL)
{
this.updateLead = function (lead_data) {
var url = BASE_URL+"/leads/update/";
var deferred = $q.defer();
$http.post(url , lead_data).then(function(response){
deferred.resolve(response.data);
});
return deferred.promise;
}
}
i call to this function from a Controller:
LeadsController.$inject = ['$scope', 'LeadsAPI'];
function LeadsController($scope , LeadsAPI)
{
LeadsAPI.updateLead({'lead_id' : res._id, 'the_lead': {'fist_name' : 'asd asd'}}).then(function (res) {
console.log(res);
});
}
i tried pass the parameters as a string ("a=b&c=d...") and added header :
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
in the run function at my App module instantiation but yet, i keep getting 405 (Method Not Allowed) error.
any ideas why and how to solve it? thank you very much all! :)
Seems the question is old and unanswered but google led me here. I hope someone will find this answer useful.
I had the same problem. $http was set to POST but server was returning error from GET request.
After checking the headers in a web inspector it shows the browser actually did two requests:
update/ 301 text/html angular.js:11442
update 405 xhr https://test.site/post/update
The first one is the one from $http and the second one is after a redirect.
As you can see the trailing slash URL is redirected to a non trailing one. With this redirect a POST request gets also changed to GET as well.
The solution is to change your request url to not contain trailing slashes:
url: BASE_URL+"/leads/update",
The GET works fine ... good
The POST returns 405 - Method not allowed
It sounds like it is doing a POST and the server you are posting to does not support POST requests to the endpoint in question
Can you please provide more information, such as the HTTP request and response headers when you make a GET request and the same for the POST request
You can access the header information via the NET tab in Firefox's Firebug or in Chrome console
Be sure that your API method is ready to handle a POST request. Maybe Angular is actually firing a POST request, but your method is expecting a GET.
If you are sure Angular is really firing a GET request instead of a POST for some reason, try to explicitly set the HTTP method on the $http object:
$http({
method: 'POST',
url: BASE_URL+"/leads/update/",
data: lead_data
}).then(function (response) {
deferred.resolve(response.data);
});

Angularjs error when trying to read title from url

I'm using AngularJS along with Node.js and I'm trying to read title from a specific url
I have something like this:
App.config(function($httpProvider) {
//Enable cross domain calls
$httpProvider.defaults.useXDomain = true;
//Remove the header used to identify ajax call that would prevent CORS from working
delete $httpProvider.defaults.headers.common['X-Requested-With'];
});
And I try to read urls title with:
$http({ url:$scope.url,method:"POST", headers: {'Content-Type': 'application/x-www-form- urlencoded'}}).success(function(data){
console.log(data);
});
But I get NetworkError: 405 Method Not Allowed and/or Cross-Origin Request Blocked:....
It doesn't matter what your client-side code is, you'll need to enable CORS on the server side to allow Cross-Origin requests.

Categories

Resources