"405 (Method Not Allowed) and Response for preflight does not have HTTP ok status Error" - http-status-code-405

I'm building a simple web application and i'm making an XMLHttpRequest() POST request call to a URL that is hosted on Azure. I'm getting the following error:
"405 (Method Not Allowed)"
"Response for preflight does not have HTTP ok status Error"
I have also enabled my CORS extension on my browser. Below is my code:
var xhr = new XMLHttpRequest();
var url = "MyURL" // URL is Correct, I verified!
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var json = JSON.parse(xhr.responseText);
console.log("Data is: " + json);
}
};
var obj = { SignId: getSignIdArr[temp] , BarCodeId: getBarCodeIdArr[temp],
BaseType: getBaseTypeArr[temp], Condition: getConditionArr[temp],
ConditionDate: getConditionDateArr[temp], Owner: getOwnerArr[temp],
Custodian: getCustodianArr[temp], FaceMaterial: getFaceMaterialArr[temp],
FacingDirection: getFacingDirectionArr[temp], Height: getHeightArr[temp],
Illuminated: getIlluminatedArr[temp], MountType: getMountTypeArr[temp],
Notes: getNotesArr[temp], Code: getCodeArr[temp],
Description: getDescriptionArr[temp], Dimensions: getDimensionsArr[temp],
Type: getTypeArr[temp], Status: getStatusArr[temp],
Support: getSupportArr[temp], RetroRefTextSymbol: getRetroRefTextSymbolArr[temp],
RetroRefBackground: getRetroRefBackgroundArr[temp],
RetroRefTestFailed: getRetroRefTestFailedArr[temp], MaterialCost: getMaterialCostArr[temp],
LabourCost: getLabourCostArr[temp], InstallationCost: getInstallationCostArr[temp],
ReflectiveCoating: getReflectiveCoatingArr[temp],
ReflectiveRating: getReflectiveRatingArr[temp],
OptimisticLockField: getOptimisticLockFieldArr[temp], GCRecord: getGCRecordArr[temp],
NewSupport: getNewSupportArr[temp], SignGroup: getSignGroupArr[temp],
RetroRefDate: getRetroRefDateArr[temp], EquipmentCost: getEquipmentCostArr[temp]
};
var data = JSON.stringify(obj);
xhr.send(data);
Any help will be greatly appreciated! Stuck in this for a while. Thanks all!

Related

post image to server using http post multipart/form-data request [flutter-web]

I am trying to upload the image to server using http package,
here is the screenshot from postman
so far I have been following this link https://rodolfohernan20.blogspot.com/2019/12/upload-files-to-server-with-flutter-web.html
and here is part of the code to send the image
var url = Uri.parse("http:xxxxxxx");
var request = new http.MultipartRequest("POST", url);
request.headers.addAll(headers);
request.fields['user_id'] = '1';
request.fields['_method'] = 'put';
request.files.add(await http.MultipartFile.fromBytes(
'file', _imageFile,
contentType: new MediaType('application', 'octet-stream'),
filename: "example"));
request.send().then((response) {
print(response.statusCode);
if (response.statusCode == 200) print("sent");
});
imageFile is List of int(List<int>) where imageFile=Base64Decoder().convert(result.toString().split(",").last);
the respond that I get is always respond status= 400, is there a way to solve this?
You can try this way:
//URL
String baseUrl = "https:xxxxx";
var request = http.MultipartRequest('POST', Uri.parse(baseUrl));
request.headers.addAll(headers);
request.files.add(
http.MultipartFile(
'file',
File(_imageFile.path).readAsBytes().asStream(),
File(_imageFile.path).lengthSync(),
filename: _imageFile.path.split("/").last,
),
);
// Other fields
request.fields['user_id'] = '1';
request.fields['_method'] = 'put';
var response = await request.send();
if (response.statusCode == 200) {
// do something...
} else {
// do something...
}

Slack WebAPI fails with not_authed

I'm attempting to post interactive messages to slack as a Bot User (using chat.postMessage, etc).
Although I am passing in the Bot Access Token (as received from the initial OAuth) I keep getting an error response stating "not_authed".
I get the same when I attempt auth.test.
I'm doing something like the following with "request" in node.js:
app.get("/testAuth/test", function(req,res){
console.log("in testAuth/test...sending test message to Slack");
var bToken = process.env.TESTBOT_ACCESS_TOKEN;
var slackMessageURL = "https://slack.com/api/auth.test";
var postOptions = {
uri: slackMessageURL,
method: "POST",
token: bToken
};
request(postOptions, (error, response, body) => {
if(error){
console.log("OOPPPPS....we hit an error in auth.test: " + error);
} else {
console.log("auth.test response: " + JSON.stringify(response));
}
});
res.send("Sent Test...check logs");
});
which results with:
auth.test response: {"statusCode":200,"body":"{\"ok\":false,\"error\":\"not_authed\"}",...
According to the Slack WebAPI docs, if I'm posting as the Bot, I should use the Bot's access token (as received from the initial oauth), but figure I'm either formatting my request incorrectly, or the token is not what Slack is expecting.
Ok, after talking with Slack support, it appears (at least) the WebAPIs I am calling don't yet support application/json. These do work with x-www-form-urlencoded.
Looking at this post
I was able to cobble together the following which auth'd successfully:
//up top
var request = require("request");
var querystring = require("querystring");
//...
app.get("/testAuth/test", function(req,res){
console.log("in testAuth/test...sending test message to Slack");
var bToken = process.env.TESTBOT_ACCESS_TOKEN;
var message = {
token: bToken
};
var messageString = querystring.stringify(message);
var messageLength = messageString.length;
var slackMessageURL = "https://slack.com/api/auth.test";
var postOptions = {
headers: {
"Content-length": messageLength,
"Content-type": "application/x-www-form-urlencoded"
},
uri: slackMessageURL,
body: messageString,
method: "POST"
};
request(postOptions, (error, response, body) => {
if(error){
console.log("OOPPPPS....we hit an error in auth.test: " + error);
} else {
console.log("auth.test response: " + JSON.stringify(response));
}
});
res.send("Sent Test...check logs");
});

Parse Response Variable Issues with HTTP Request and Cloud Code

I am trying to run an HTTP Request in an afterSave. It executes correctly, but im getting errors with the response variable I was told to put in the end.
Here is the code
Parse.Cloud.afterSave("ArtPiece", function(request) {
var artistURL = 'http://www.gallery-admin-dev.iartview.com/Gilmans/imageSave.php';
var artPiece = request.object;
if (typeof request.image === "undefined") {
var pieceName = artPiece.get("piece_name");
var url = artPiece.get("imageURL");
Parse.Cloud.httpRequest({
url: artistURL,
params: {
pieceName : pieceName,
url : url
},
success: function(httpResponse) {
response.success();
},
error: function(httpResponse) {
response.error('Request failed with response code ' + httpResponse.status)
}
});
}
});
The problem is the success and error functions.
Things I have tried that have not worked:
Putting response as a second parameter in the afterSave Call (it says can not call .success of an undefined variable)
Getting rid of the response lines of code (Result: success/error was not called)
Calling Response as its own function response('Request failed with response code ' + httpResponse.status) it just says response is undefined.
I dont really care about having any response or not, I just want the code to work properly.
How is this 'response' variable supposed to be set up?
Thank you!
There was an extra url in the parameters, a reference to a probably undefined artistURL...
Parse.Cloud.afterSave("ArtPiece", function(request) {
var artistURL = 'http://www.gallery-admin-dev.iartview.com/Gilmans/imageSave.php';
var artPiece = request.object;
if (typeof request.image === "undefined") {
var pieceName = artPiece.get("piece_name");
var url = artPiece.get("imageURL");
var params = { pieceName : pieceName };
return Parse.Cloud.httpRequest({ url: artistURL, params: params });
}
});

Pass a url as a parameter with the GET methoid in the django-rest framework?

I am going to pass a url as a GET parameter to the restful API, but it can not match the url pattern, therefore 404 returns.
I use the django-rest framework as the server side.
Here is the urls.py
url(r'^method/?P<url>(https?:\/\/(www\.)?[-a-zA-Z0-9#:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9#:%_\+.~#?&//=]*))$',views.Method.as_view()), name='method'),
And the client xhr code is something like this.
var xhr = new XMLHttpRequest();
// url is like https://storage.googleapis.com/xxx/cccc/abc.txt
xhr.open('GET', 'method/' + url, true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
if (this.status == 200) {
// do something
}
};
xhr.send();
The regex is ok, but still returns 404 by the server.
Even though I pass the request url something like
xhr.open('GET', 'method?=' + url, true);
It still returns 404 not found.
What is the proper way to do this?
Thank you!
Change your client xhr code like:
var xhr = new XMLHttpRequest();
var url = 'https://storage.googleapis.com/xxx/cccc/abc.txt';
xhr.open('GET', 'method/?url=' + encodeURIComponent(url), true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
if (this.status == 200) {
// do something
}
};
xhr.send();

XDomainRequest Errors, but developer tools shows response body

I am using XDomainRequest to send a cross domain request. The onerror handler is firing; however, nothing is logged and when tracing network in developer tools I can see the response in the response body.
Anyone have any ideas? Below is the code I am using. Thanks in advance for any help.
var createCORSRequest = function(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Most browsers.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// IE8 & IE9
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
};
var url = 'https://myurl';
var method = 'GET';
var xhr = createCORSRequest(method, url);
xhr.onload = function() {
// Success code goes here.
//alert("load");
alert(xhr.responseText);
};
xhr.onprogress = function(){
alert("Progress");
}
xhr.onerror = function() {
alert("error");
};
xhr.send();
XDomainRequest object does not provide anyway to determine what is the status code of error, and returns empty string in xdr.responseText.

Resources