JSON post request shows 405 not allowed error (using XMLHttpRequest()) - javascript

here's my js code:
var myreq=new XMLHttpRequest();
myreq.open("GET","https://<username>.github.io/test/data/data.json",true);
myreq.onload =function(){
console.log(JSON.parse(myreq.response));
}
myreq.send();
const data={
"name": "jayant",
"job": "leader"
};
function here()
{
var myreq1=new XMLHttpRequest();
myreq1.onload = () => {
// print JSON response
if (myreq1.status >= 200 && myreq1.status < 300) {
// parse JSON
const response = JSON.parse(myreq1.responseText);
console.log(response);
}
};
myreq1.open("POST",'https://<username>.github.io/test/data/data.json');
myreq1.setRequestHeader('Content-Type', 'application/json');
myreq1.send(JSON.stringify(data));
}
Function here is called on a button click
and here's my JSON code:
[
{
"name1":"jayant",
"age":58,
"pass":"LetsLearnJson"
},
{
"name1":"jayant2",
"age":45,
"pass":"ok"
},
{
"name1":"jayant3",
"age":24,
"pass":"test"
},
{
"name1":"abcd",
"age":75,
"pass":"abcd"
}
]
I am getting this error when I try to post:
POST https://<username>.github.io/test/%22https://<username>.github.io/test/data/data.json%22 405
Please help. I have tried many things already available online but nothing seems to work

The 405 Method Not Allowed Error occurs when the web server is configured so that you cannot perform a specific action for a specific URL. It is an HTTP response status code that indicates that the request method is known to the server, but is not supported by the target resource.

Related

Jest XMLHttpRequest mock request shows error

I have following function.
export function sendWeatherrequest(countryName) {
let xmrRequest = new XMLHttpRequest();
xmrRequest.onload = requestListener;
xmrRequest.onerror = requestError;
xmrRequest.open('get', generateUrl(name), true);
xmrRequest.send();
}
function requestListener() {
let data = JSON.parse(this.responseText);
displayPage(data);
}
I am using jest for unit test.
As, i read somewhere that it is bad idea to test original XMLHttpRequest. Is it true?
So, created following from XHR testing in Jest answer
let open, send, status, onload, setRequestHeader, response;
function createXHRmock() {
open = jest.fn();
status = 200;
response = JSON.stringify([{
title: 'some data.',
weather: 'wind'
}]);
send = jest.fn().mockImplementation(function(){
onload = this.onload.bind(this);
onerror = this.onerror.bind(this);
});
const xhrMockClass = function () {
return {
open,
send,
status,
setRequestHeader,
response
};
};
window.XMLHttpRequest = jest.fn().mockImplementation(xhrMockClass);
}
it('XHR success', () => {
createXHRmock();
expect(open).toBeCalledWith('GET', 'http://example.com', true);
expect(send).toBeCalled();
onload();
});
But, i am getting following error.
XHR success
expect(jest.fn()).toBeCalledWith(expected)
Expected mock function to have been called with:
["GET", "http://example.com", true]
But it was not called.
My be i done some stupid mistake but, can't figureout. I am very poor in unit testing.
Any help would be greatly appreciated.
Looking at the answer you linked, there's a bit in the example answer:
createXHRmock();
// here you should call GET request
expect(open).toBeCalledWith('GET', 'http://example.com', true);
In between the two statements, you need to invoke your sendWeatherrequest, and modify your expect(open) expect the URL that comes back from your generateUrl function.
e.g.
createXHRmock();
sendWeatherrequest('FR')
expect(open).toBeCalledWith('GET', 'http://theweather.net/france', true);

In a Camunda process, How can I retrieve a boolean value from JSON using JavaScript and Spin?

I have a service task which calls a REST API; the API is returning the following JSON:
{
"success": true,
"message": null,
"details": [],
"errors": [],
"transactions": []
}
The service task has a JavaScript output parameter to process the JSON output:
var statusCode = connector.getVariable("statusCode");
if (statusCode != 200) {
throw new Error(connector.getVariable("response"));
}
else {
var output = S(connector.getVariable("response"));
output.prop("success").value==true; // Problem line
}
I have sent the output to a process variable and confirmed that it contains the JSON above. However, I cannot get this output to ever register as true for the subsequent forking of the process. I have tried all of the following:
output.prop("success");
output.prop("success").value;
output.prop("success").value==true;
output.prop("success").value===true;
output.prop("success").value=="true";
Can anyone help with getting this right?
I got help with this in the Camunda forum here. My code now reads as below, and works as desired:
var statusCode = connector.getVariable("statusCode");
if (statusCode != 200) {
throw new Error(connector.getVariable("response"));
}
else {
var output = S(connector.getVariable("response"), "application/json");
output .prop("success").boolValue();
}

Serverless CORS preflight request failed - AWS API Stripe

I have spent about 2 weeks trying to debug this but no luck.
I have created a lambda function using python that creates a charge. This works fine with Stripe Checkout's simple script. It invokes it and returns the response without any issues (Python).
try:
stripe.api_key = "*******PRIVATE KEY***********"
Tokenstring = event.get('body')
Stripe_List = Tokenstring.split('=')
Token = Stripe_List[1].split('&')[0]
Email = Stripe_List[-1]
Email = Email.replace('%40', '#')
charge = stripe.Charge.create(
amount=100,
currency="gbp",
description="Example charge",
source=Token,
receipt_email=Email
)
print('Full SUCCESSFUL Transaxn Info ==== {}'.format(event))
return {
"statusCode": 302,
"headers": {
"Location": "https://example.com/#success"
}
}
This is invoked very simply in the html body with <form action="https://XXXXXXX.execute-api.eu-central-1.amazonaws.com/beta" method="POST">
Now, when I try to use the custom stripe checkout code, I get:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
My javascript code is:
var handler = StripeCheckout.configure({
key: '*****PRIVATE KEY*****',
image: 'logo.png',
locale: 'auto',
token: function(token) {
var xhr = new XMLHttpRequest();
xhr.open("POST","https://XXXXXXX.execute-api.eu-central-1.amazonaws.com/beta", true);
xhr.setRequestHeader('Content-Type','application/json');
xhr.setRequestHeader('Access-Control-Allow-Origin','*');
xhr.onreadystatechange = handler;
xhr.send(JSON.stringify({
body : token
}));
}
});
I have set up OPTIONS in Amazon's API Gateway to respond and have enabled CORS on amazon API gateway.
How can I pass the pre-flight request and let lambda execute the function?
Aside from enabling CORS on the API Gateway Console, your Lambda function itself has to return those CORS headers.
return {
"statusCode": 302,
"headers": {
"Location": "https://example.com/#success",
"Access-Control-Allow-Origin": "*",
}
}

Response in file upload with Jersey and ExtJS

I have a method which save an image file in the database as a BLOB file. The method works fine, but when I get the callback in ExtJS filefield component, it always goes through failure function and I don't know what I have to respond to go through success function, this is my code:
Server method:
#POST
#Path("/upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces({ MediaType.APPLICATION_JSON })
public ServiceResponse uploadFile(#QueryParam("id") Long iconId, FormDataMultiPart form) {
CatIcon icon;
if (iconId != null) {
icon = catIconBean.getOne(iconId);
} else {
icon = new CatIcon();
}
byte[] image = form.getField("iconBmp").getValueAs(byte[].class);
if (image.length != 0) {
MultivaluedMap<String, String> headers = form.getField("iconBmp").getHeaders();
String type = headers.getFirst("Content-type");
List<String> list = Arrays.asList("image/gif", "image/png", "image/jpg", "image/jpeg",
"image/x-icon", "image/bmp");
if (list.contains(type)) {
icon.setIconBmp(image);
icon.setType(type);
}
}
icon.setDescription(form.getField("description").getValue());
icon.setFileName(form.getField("fileName").getValue());
icon = catIconBean.saveIcon(icon);
ServiceResponse sr = new ServiceResponse();
sr.httpResponse = true;
return sr;
}
What I have to return in the code above?
Client:
uploadIcon : function(item, e, eOpts) {
var me = this;
var form = this.getDetail().getForm();
var valid = form.isValid();
if (!valid) {
return false;
}
var values = form.getValues();
if(values) {
form.submit({
url : myApplication.defaultHost() + 'icon/upload?id=' + values.id,
waitMsg : 'Uploading...',
success : function(form, action) {
me.onCompleteSaveOrDelete();
},
failure : function(form, action) {
me.onCompleteSaveOrDelete();
}
});
}
},
I write the same function, me.onCompleteSaveOrDelete(), in both callback functions to make it be called, that's the method which I want to be called in success.
Greetings.
UPDATE:
I did almost the same Alexander.Berg answered. The only difference was that I write #Produces({ MediaType.APPLICATION_JSON }) instead of #Produces({ MediaType.TEXT_HTML }), because I need Json Response. But when I debug in chrome and check the response, I get this:
In failure:
failure : function(form, action) {
me.onCompleteSaveOrDelete();
}
In action param, within responseText:
"{"data":"{\"success\":true}","httpResponse":true,"totalCount":0}"
But It's still going through failure...I think I'm very close, any help??
Greetings.
The fileupload in Extjs is more tricky, because it is using iframe and submit, not a real ajax request for uploading files.
Try this on Server method:
#POST
#Path("/upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces(MediaType.TEXT_HTML)
public String uploadFile(#QueryParam("id") Long iconId, FormDataMultiPart form) {
(...)
JSONObject json = new JSONObject();
json.put("success", true);
json.put("msg", "Success");
return json.toString();
}
this is because the upload accepts Content-Type text/html,
see Example at http://docs.sencha.com/extjs/4.2.2/#!/api/Ext.form.field.File -> Example Usage -> Live Preview
Use Firefox browser with Firebug plugin and on Net tab the following URL -> http://docs.sencha.com/extjs/4.2.2/photo-upload.php
Response Headersview source
(...)
Content-Type text/html
(...)
Request Headersview source
Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
(...)

JavaScript Send JSON to Google API

I am new to the Google API (Calendar V3) and I have the authorization through obtaining a token working. I am using a get request to get the users calendar_Id in which I want to send in a POST request in order to add an event to the calendar.
Here is what I am working with:
var json_body = {
"end": {
"date": "2013-09-06"
},
"start": {
"date": "2013-09-06"
},
"summary": "test event 1"
};
var json_string = JSON.stringify(json_body);
http.setRequestHeader("Content-Type", "application/json");
http.setRequestHeader("Authorization","Bearer " + access_key);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert("in here");
alert(http.responseText);
}
}
http.send(json_string);
The response I am getting is:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "parseError",
"message": "Parse Error"
}
],
"code": 400,
"message": "Parse Error"
}
}
I know that the access_key authorization header is correct since it is not giving me the authorization error. I have ran this JSON structure in Googles API Explorer tool and it adds an element to my calendar correctly. I am assuming that the way I am building my JSON is incorrect. Any ideas?
Thank you in advance.
EDIT:
I found the correct solution. I was mis-using a parameter in the url request. The code above works in case anyone stumbles upon this for reference in the future.

Categories

Resources