The 'Access-Control-Allow-Origin' header contains multiple values (Plesk on Windows) - javascript

I have the following code in JS:
// Function to feed the API
function FeedAPI() {
// Define the API endpoint URL
var apiUrl = "https://ifthenpay.com/api/gateway/paybylink/XXX-XXXX";
// Define the JSON API body
var apiData = {
"id": "1234",
"amount": ValueSelected(),
"description": $('#name').val(),
"lang": "en",
"expiredate": "",
"accounts": "",
"selected_method": PaymentSelected()
};
console.log("API data: ", apiData);
// Use jQuery's $.ajax() function to make the request
$.ajax({
type: "POST",
url: apiUrl,
data: JSON.stringify(apiData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
console.log("API response: ", response);
},
error: function(xhr, status, error) {
console.error("Error: ", error);
}
});
}
But get this error:
Access to XMLHttpRequest at 'https://ifthenpay.com/api/gateway/paybylink/XXX-XXXX' from origin 'https://example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed.
I'm using Plesk on Windows and already tried to set my web.config file to the following:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>
</httpProtocol>
At this point, I tried everything... Can someone help??

So, I fixed my issue by just changinging the method of the API Integration to "GET".
Here is the code:
function FeedAPI() {
// Define the API endpoint URL
var apiUrl = "https://ifthenpay.com/api/gateway/paybylink/get";
// Define the query parameters
var apiParams = {
"gatewaykey": "XXX-XXXX",
"id": "1234",
"amount": ValueSelected(),
"description": $('#name').val(),
"lang": "en",
"expiredate": "",
"accounts": "XXX|YYY;MBWAY|XXX-XXXXX",
"selected_method": PaymentSelected()
};
console.log("API params: ", apiParams);
// Use jQuery's $.ajax() function to make the request
$.ajax({
type: "GET",
url: apiUrl,
data: apiParams,
success: function(response) {
console.log("API response: ", response);
window.open(response.link, "_blank");
},
error: function(xhr, status, error) {
console.error("Error: ", error);
}
});
}

Related

how to post data to web service

Problem Description:- i am trying to call web services of different domain(i.e. Systems are not connected locally with each other) so i am getting error:-"Failed to load https://sap.atlassian.net/: Response for preflight is invalid (redirect)"
var username = "pra#sap.com";
var password = "Sa8";
$.ajax({
type: 'POST',
data: data1,
url: 'https://sap.atlassian.net',
dataType: 'json',
contentType: "application/json",
crossDomain: true,
ProcessData: true,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Methods": "POST, GET, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "accept, X-Custom-Header, x-requested-with, X-Auth-Token, Content-Type"
},
beforeSend: function(xhr) {
xhr.setRequestHeader("X-Atlassian-Token", "no-check");
xhr.setRequestHeader('Authorization', "Basic" + btoa(username + ":" + password));
},
success: function(data) {
console.log("success");
},
error: function(e) {
console.log(e);
}
});
First, you might need to double-check URL. There must be some relative URL as well.
This is related to preflight. See https://www.gyanblog.com/gyan/39-explaining-issue-response-preflight-request-doesnt-pass-access-control-check
Can you post detailed stacktrace?
PS: Its always bad practice of putting your username/password openly. You should immediately change your password!

How to get headers element in node js

I would like to get headers element in server side with node js I try these two codes in client side:
CODE 1
var token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0ayI6IjU5Mjg0YjQ0MzNhNjU2MmRlNDI1ZGU5MCIsImlhdCI6MTQ5NjY5NjA1NiwiZXhwIjoyOTkzMzk1NzEyfQ.BQskPVT-h-Io4p3Hqraq2qRmVlp_pWAEw5rnIIEA4vk';
$.ajax({
url: 'YourRestEndPoint',
headers: {
'Authorization':'Basic' + token
},
method: 'POST',
dataType: 'json',
data: YourData,
success: function(data){
console.log('succes: '+data);
}
});
Code 2:
$.ajax({
url: "http://localhost/PlatformPortal/Buyers/Account/SignIn",
data: { signature: authHeader },
type: "GET",
beforeSend: function(xhr){xhr.setRequestHeader(
'Authorization':'Basic' + token);
},
success: function() { alert('Success!' + authHeader); }
});
And here the code server:
res.header("Access-Control-Allow-Origin", "*");
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.header("Access-Control-Allow-Headers", "Authorization");
console.log(req.headers['authorization']);
I can't get the token in the server side.
In Code 1, you have 'Authorization' as the property name in your header. However, in your code, you console.log 'authorization'.
Try the same capitalization of both. Let me know if the capital was an error with copying and pasting.

Response for preflight has invalid HTTP status code 400 - aspx

I am writing both server and client using visual studio 2015.
The following problem occurs in Chrome and FireFox, but works perfect in Explorer.
I am doing a Rest post call using AJAX to my server, the AJAX code:
function CheckIntegrityExecution() {
var request = ...
var reqJson = JSON.stringify(request);
$.ajax({
type: "POST",
url: "http://localhost:55857/api/post/flow",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: reqJson,
success: function (jsonData) {
...
},
error: function () {
alert("error");
}
});
}
Initially I was getting 405 error, and this was fixed with adding
var cors = new EnableCorsAttribute("http://localhost:55857", "*", "*");
config.EnableCors(cors);
To the Register function in Global.asax:
public static void Register(HttpConfiguration config)
Now I getting the following error:
XMLHttpRequest cannot load http://localhost:55857/api/post/flow. Response for preflight has invalid HTTP status code 400
The method signature in my server is
[Route("api/post/flow")]
public HttpResponseMessage PostCommand([FromBody] dynamic value)
And I have these configuration in my Web.config in the WebApi.
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="OPTIONS, TRACE, GET, HEAD, POST, PUT" />
<add name="Access-Control-Allow-Headers" value="Origin, Content-Type, Authorization, Accept, X-Requested-With" />
</customHeaders>
I notice that if I delete
contentType: "application/json; charset=utf-8",
from the Ajax request I will work, but I will not get the data in my server.
I have no ideas what to do, tried everything.
The solution was to add the following to the Global.asax file
protected void Application_BeginRequest()
{
var context = HttpContext.Current;
var response = context.Response;
if (context.Request.HttpMethod == "OPTIONS")
{
response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
response.End();
}
}

Backbone with Oauth2 granttype password

I want to call an OAuth2 service with grant_type password.
I am using Backbone with Jquery.
Parameters for the POST:
grant_type=password
client_id=[YOUR_APP_ID]
client_secret=[YOUR_CLIENT_SECRET]
username=[USER_NAME]
password=[USER_PASSWORD]
I have tried several NPM plugins but all give error.
I have created a custom post AJAX but this also does not work:
var results = $.ajax({
// The URL to process the request
url : "https://app1pub.smappee.net/dev/v1/oauth2/token",
type : "POST",
data : {
grant_type : "password",//jshint ignore:line
username: "myuser",
password: "secret",
client_id: "myclient",//jshint ignore:line
client_secret: "clientSecret"//jshint ignore:line
},
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Bearer $token");
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
},
dataType: "json",
contentType: "application/x-www-form-urlencoded",
success: function(response) {
//console.log(response);
console.log(response.access_token);//jshint ignore:line
data.access_token = response.access_token;//jshint ignore:line
//tokenGranted();
}
});
return results.responseText;
(see fiddle: https://jsfiddle.net/gf70sss5/)
All give me the error:
"XMLHttpRequest cannot load https://app1pub.smappee.net/dev/v1/oauth2/token. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access."
Does anyone know a NPM plugin which works with the password granttype? Preferrably with an example. I have tried a few (like simple-oauth2) but I can't get any working.
Or an AJAX call which does work? Or what I am doing wrong?
Try this, but i've still a problem with the "Access-Control-Allow-Origin" error
var url = 'https://app1pub.smappee.net/dev/v1/oauth2/token';
// ajax call
$.ajax({
type: "POST",
url: url,
data: {"grant_type": "password", "client_id": client_id, "client_secret": client_secret,"username": username,"password": password},
beforeSend : function(xhr) {
xhr.setRequestHeader("POST", "/dev/v1/oauth2/token HTTP/1.1");
xhr.setRequestHeader("HOST", "app1pub.smappee.net");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
},
error : function() {
// error handler
},
success: function(data) {
// success handler
alert(data["access_token"])
}

Update (PUT) a JSON object with ajax - PrestaShop

I am trying to update a JSON object (e.g: customer). But, I have the following error:
"NetworkError: 405 Method Not Allowed - http://prestashop/api/..."
This is my code (index.js):
var testWebService = angular.module('testWebService', []);
testWebService.controller('testWebServiceCtrl', function ($scope, $http) {
var $baseDir = "http://prestashop/api";
var $objectDir = "customers";
var $idObjectDir = "1";
var $keyDir = "F517VWPRREG7TA25DEY8UIZT8V79E5OV";
var $urlDir = $baseDir + "/" + $objectDir + "/" + $idObjectDir + "?ws_key=" + $keyDir + "&output_format=JSON";
// TEST DE LA METHODE PUT SUR L ID D UN CUSTOMER
$.ajax({
type: "PUT",
url: $urlDir,
dataType: "json",
async: false,
contentType: "application/json; charset=utf-8",
data: {"id": "93"},
crossDomain: true,
success: function () {
console.log("Ok PUT");
},
error: function() {
console.log("Erreur PUT");
}
});
});
Before, I tried to GET the id of an object (same: customer) and I succeeded with an almost similar method.
I precise that I gave rights about "customer" in Advanced Settings / webservice (for method GET, PUT, POST ...).
Thanks in advance for your help, I tried so many things, but whitout success.
PS: If you have any suggestion about my code to "clean" it, you were pleased.
My webservice JSON:
{"customer":{"id":1,"id_default_group":"3","id_lang":"1","newsletter_date_add":"2013-12-13 08:19:15","ip_registration_newsletter":"","last_passwd_gen":"2015-06-08 03:38:27","secure_key":"7036cdf99ea12125ad1b3789f298f686","deleted":"0","passwd":"2e372235eb5213bc004ce72bcfef16a2","lastname":"DOE","firstname":"John","email":"pub#prestashop.com","id_gender":"1","birthday":"1970-01-15","newsletter":"1","optin":"1","website":"","company":"","siret":"","ape":"","outstanding_allow_amount":"0.000000","show_public_prices":"0","id_risk":"0","max_payment_days":"0","active":"1","note":"","is_guest":"0","id_shop":"1","id_shop_group":"1","date_add":"2015-06-08 09:38:27","date_upd":"2015-06-08 09:38:27","associations":{"groups":[{"id":"3"}]}}}
EDIT:
When I tried with the method GET, I did:
$.ajax({
type: "GET",
url: $urlDir,
dataType: "json",
async: false,
success: function (data) {
$scope.customer1 = data;
console.log("Ok GET");
console.log(data);
},
error: function() {
console.log("Erreur GET");
}
});
Reading the status code definition of the http protocol, try adding the following property to the ajax request:
$.ajax({
type: "PUT",
...
beforeSend: function (xhr) {
xhr.setRequestHeader("Allow", "GET, HEAD, PUT, DELETE");
},
...
});
PS: If you have CORS disabled on your server, look this answer and set the headers to allow your server access to requests from different origins.

Categories