Calling a Rest API from tfs extension with JScript - javascript

I am basicly using 3 diffrent JS methods to get the data from the api but they return the error 405: Method Not Allowed but server has the get method in it as allowed. It is using path for the variable so I am wondering if it is related to that.
Here are the Codes for Methods that i call the API.
Fetch Method;
function getCompleted(queryParam) {
$('#loader').removeClass('hidden');
$('#loaded').addClass('hidden');
fetch("****/fullprofile/" + queryParam, {
method: "GET", headers: {
"User": "*****",
"Content-Type": "application/json"
}
})
.then((data) => {
const contentType = response.headers.get('content-type');
console.log(contentType);
return data.json()
})
.then(function (result) {
ResponseBody = result;
$('#loader').addClass('hidden');
$('#loaded').removeClass('hidden');
}).catch(function () {
$('#loader').addClass('hidden');
$('#loaded').removeClass('hidden');
});
}
HTTP Request Method;
function httprequest(queryParam2) {
$('#loader').removeClass('hidden');
$('#loaded').addClass('hidden');
var xmlhttp = new XMLHttpRequest();
xmlhttp.withCredentials=true;
var url = "*****/fullprofile/";
xmlhttp.onreadystatechange = function (data) {
console.log(this.responseText);
console.log(data);
}
xmlhttp.open("GET", url + queryParam2);
xmlhttp.setRequestHeader("User", "*****");
xmlhttp.send();
}
Ajax Method;
function ajax(queryParam3) {
$.ajax({
url: "****/fullprofile/" + queryParam3,
"method":"GET",
"headers":{
"User":"EBT\\****"
},
success: function (data) {
ResponseBody = data;
console.log(data);
}
});
}
Thank you all for the advices and help.

the reason was sending with headers; it returns options that needs to be responded again and it wasn't worth doing in JS so i decided to make a gateway api to use the api i have with header.
Thank you.

It is possible that the resource you are trying to consult does not use the verb GET.
you have to confirm with which verb the resource is obtained
Look here:
405 Method Not Allowed MDN Docs
Confirm in the documentation of the api with which verb that resource is requested. I could be POST, PUT etc
Here you can look explanation

Related

cross origin for amazon lambda function from localhost in gatsby site

I have the following code which works when I run it as a local serverless function with netlify dev, but I need it to run cross origin from a dev server to the hosted server function. I put the function in a aws lambda function but I am getting a cross origin blocked error on my https:dev.website.com, I thought I have the correct headers in the return object so not sure why I am getting a cross origin error.
Any help would be great
const sanityClient = require("#sanity/client");
const client = sanityClient({
projectId: "random-id",
dataset: "production",
useCdn: true,
});
exports.lambdaHandler = async (event, context) => {
var body = JSON.parse(event.body);
//console.log(body.price_id)
try {
const checkPriceId = async (test) => {
const query = `*[_type == "products" && price_id == "${body.price_id}"]`;
const documents = await client.fetch(query, {}); // this could throw
return documents.map((document) => document.sold);
};
var ok = checkPriceId().then((test) => {
return new Promise(function (resolve, reject) {
//console.log(test) // this will log the return value from line 7
console.log(test);
resolve(test);
});
});
var bools = await ok;
// prettier-ignore
return {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Methods':'GET, POST, OPTION',
},
body: JSON.stringify({
sold: bools,
}),
};
} catch (err) {
return { statusCode: 500, body: err.toString() };
}
};
This is my request to the function if that helps
var fetchUrl = https://random.executue-api.aws.com/prod/sold //not exact
var fetchData = async function () {
const response = await fetch(fetchUrl, {
method: "post",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
price_id: final,
}),
})
.then(res => {
return res.json()
})
.catch(error => console.log(error))
return response
}
Update:
I tried adding cors the way suggested in the answer below, but it failed seen below so I tried manually adding the method response seen after.
I still get a cross domain error. And I have changed the domain so it is now https as well. Really stuck here.
I was looking into this more, and it seems like before it does the actual post it does a cors check at the options method, so I added in the same access control headers, and deployed but did not work. Don't quite get this.
Your headers look ok to me. (note: If you mix HTTP and HTTPS you are most likely to get a mixed content error in the client). If it is ONLY a CORS issue that you are seeing in the console in the web browser, then you might not have configured the API Gateway correctly in AWS.
In AWS, go to API Gateway and you should see something like the below:
Make sure that you enable CORS and then redeploy.
UPDATE:
Just looking at a previous implementation of a lambda function I setup with AWS. The headers I declared were as follows:
headers: {
"Content-Type" : "application/json",
"Access-Control-Allow-Origin" : "*",
"Allow" : "GET, OPTIONS, POST",
"Access-Control-Allow-Methods" : "GET, OPTIONS, POST",
"Access-Control-Allow-Headers" : "*",
"Access-Control-Allow-Credentials" : true
}
Your headers look OK to me though. However, when you created the method in the API Gateway, did you select Use Proxy Lambda Integration? (see screenshot).
Your client side fetch request looks ok. For reference mine was:
const url = 'your url';
const options = {
method: 'POST',
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
};
fetch(url, options).then(res => res.json());
Unrelated to this issue, but its not advisable to mix Async/Await with .then promise chaining. But this isn't the issue you are having. Just something to note.
Check the values from your Integration Response / try setting them manually for both OPTIONS and POST (and if that works, make sure you are passing through the response correctly from the lambda).
Your POST action should only require the Access-Control-Allow-Origin header. The other two (Access-Control-Allow-Methods, Access-Control-Allow-Headers) belong in the OPTION action. See this writeup, and note the full example exchange for a preflighted request (in grey): https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#preflighted_requests

Fetch API SyntaxError: Unexpected token { in JSON at position 169681

Im trying to make an HTTP request using fetch, but it's blowing up with the error: "SyntaxError: Unexpected token { in JSON at position 169681". This is my request function:
async getOportunidades() {
try {
const response = await fetch('https://gcsupport.internal.vodafone.com/bpa/webservices/GCCRM.asmx/GetCardsLeadsList',
{
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: 'POST',
body: JSON.stringify({userId: 29188,tipoAplic:'T'})
});
const data = await response.json();
this.listaOportunidades = data;
return data
} catch(e) {
console.log(e);
}
}
Looking at the response at Chrome developer tools all seems fine:
and after inspecting it seems I am receiving my json data as expected, and the json string is well formed, but for some reason it "breaks" on position 169681.
Is there like a size limit on the response?!
Just for the sake of my sanity I tried to make the same request using Jquery AJAX and everything runs fine!! Thing is, I don't want to use Jquery on my project. Anyone more experienced with Fetch has any idea why this is happening?
*********MY AJAX CALL********
$.ajax({
url:'https://gcsupport.internal.vodafone.com/bpa/webservices/GCCRM.asmx/GetCardsLeadsList',
type: 'POST',
data: {userId: 29188, tipoAplic: 'T'},
success: function(data) {
console.log(data)
},
error: function(xhr, status, error) {
console.log(xhr, status, error)
}
})
******webservice code*******
Sorry if this is a duplicate question but all the issues I could find were related to "Unexpected token < at position 0" which is not my case.
Thanks in advance
Cheers
Your web service is not handling JSON requests correctly. I've created a fetch example below that uses form data that should work. $.ajax interprets the object given as form data which is why it works.
What's happening is that your web service outputs BOTH data generated from JSON body and form data. It needs to be fixed to immediately return after handling JSON body, and not continuing to try to interpret form data (which in the case of a JSON body is blank).
tl;dr Web service is bugged. Does not end writing response after using JSON body data to generate response. So, after .write(responseFromJSONData()) it doesn't return and break, and tries to continue to .write(responseFromFormData([blankFormData])), resulting in two JSON objects being attached to your response.
async getOportunidades() {
try {
const response = await fetch('https://gcsupport.internal.vodafone.com/bpa/webservices/GCCRM.asmx/GetCardsLeadsList',
{
headers: {
'Accept': '*/*',
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
method: 'POST',
body: new URLSearchParams({userId: 29188,tipoAplic:'T'})
});
const data = await response.json();
this.listaOportunidades = data;
return data
} catch(e) {
console.log(e);
}
}
var data = JSON.stringify({"userId":29188,"tipoAplic":"T"});
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function() {
if(this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", "https://gcsupport.internal.vodafone.com/bpa/webservices/GCCRM.asmx/GetCardsLeadsList");
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(data);
Try this one.

how to use fetch api in javascript to get response from C# Web method?

Java script Code :
var AllTeams;
function GetAllTeams_ProductSamplePerClass() {
return fetch("../Pages/Product.aspx/GetAllTeams", {
method: 'POST',
dataType: 'MyTeam'
}
).then(response => {
AllTeams = response.json();
console.log('success getall teams', response);
console.log('teams', AllTeams);
return AllTeams;
}).catch(error => {
console.log('Error in getall teams', error);
})
}
C# Method in aspx file :
[WebMethod]
public static List<MyTeam> GetAllTeams()
{
TeamServiceClient TeamSvc = new TeamServiceClient("wsHttpBinding_TeamWsEndPoint");
try
{
return TeamSvc.GetAllTeams();
}
catch
{
TeamSvc.Abort();
return null;
}
finally
{
TeamSvc.Close();
}
}
After search one day and keep trying and test , i found the issue that made fetch api not reach to the server is this line was not in javascript headers: {
'Accept': 'application/json',
'Content-type': 'application/json; charset=utf-8'
}
this made the response not html response as before but made the response object that came from web method
thanks #David for your help
the link i searched and found the solve :
Fetch API call causes new Asp.net session

Send same header to different requests - AngularJS

I was wondering if there is any way to send the same header to different requests.
I saw this AngularJS $http custom header for all requests but http interceptor is for all http requests and I don't want that each http request get this header.
There is other way to do this for different request without sending it manually for each request?
Sorry for my english and thanks in advance!
Yes you can ! below is an example straight from the Docs:
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': undefined
},
data: { test: 'test' }
}
$http(req).then(function(){...}, function(){...});
You can set different headers for each of your $http calls !
you can still use http interceptor with check on request url
function HttpInterceptor() {
var interceptor = {
request: function (request) {
if (request.url === 'request_url1' || request.url === 'request_url2'){
request.headers['custom_header'] = 'this is conditional header';
}
return request;
},
response: function (response) {
console.log(response);
return response;
}
};
return interceptor;
}

Receive and process JSON using fetch API in Javascript

In my Project when conditions are insufficient my Django app send JSON response with message.
I use for this JsonResponse() directive,
Code:
data = {
'is_taken_email': email
}
return JsonResponse(data)
Now I want using Javascript fetch API receive this JSON response and for example show alert.
I don't know how to use fetch API to do this. I want to write a listener who will be waiting for my JSON response from Django App.
I try:
function reqListener() {
var stack = JSON.parse(data);
console.log(stack);
}
var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
I want to compare JSON from my Django app with hardcoded JSON:
For example:
fetch( 'is_taken_email': email) - > then make something
OR
receive JSON from my Django app and as AJAX make it:
success: function(data) { if (data.is_taken_email) { make something; }
Thanks in advance!
A fetch API is provided in the global window scope in javascript, with the first argument being the URL of your API, it's Promise-based mechanism.
Simple Example
// url (required)
fetch('URL_OF_YOUR_API', {//options => (optional)
method: 'get' //Get / POST / ...
}).then(function(response) {
//response
}).catch(function(err) {
// Called if the server returns any errors
console.log("Error:"+err);
});
In your case, If you want to receive the JSON response
fetch('YOUR_URL')
.then(function(response){
// response is a json string
return response.json();// convert it to a pure JavaScript object
})
.then(function(data){
//Process Your data
if (data.is_taken_email)
alert(data);
})
.catch(function(err) {
console.log(err);
});
Example using listener based on XMLHttpRequest
function successListener() {
var data = JSON.parse(this.responseText);
alert("Name is: "+data[0].name);
}
function failureListener(err) {
console.log('Request failed', err);
}
var request = new XMLHttpRequest();
request.onload = successListener;
request.onerror = failureListener;
request.open('get', 'https://jsonplaceholder.typicode.com/users',true);
request.send();
Example of Using Listener as setInterval (I'm not sure that you want to do something like this, it's just to share with you)
var listen = setInterval(function() {
fetch('https://jsonplaceholder.typicode.com/users')
.then(function(response) {
return response.json();
})
.then(function(data) {
if (data[0].name)
console.log(data[0].name);
})
.catch(function(err) {
console.log(err);
});
}, 2000);//2 second
I am not familier with Django, but I hope this could help you.

Categories

Resources