I am trying to solve the problem of cross-domain, whenever I change my code, it never works and I think there must be something wrong with my ajax code, please check in the code, and give me some advice, thank you.
function login(url,name,password){
console.log("login");
console.log(url);
var tips = document.getElementById('tips');
$.ajax({
url: url,
type:"POST",
headers: {
"Content-Type": "application/json"
},
data:{
"user_code" : name,
"user_key" : password
},
dataType: "json",
// xhrFields: {
// withCredentials: true
// },
success:function(data){
if(data.token == undefined){
console.log(data);
tips.innerHTML = "错误";
}else{
saveToken('token',data.token,1);
saveToken('user_id',data.user_id,1);
checkToken(data.token);
}
},
error: function(msg){
console.log(msg);
console.log("fail");
}
});
}
Append in server response in header field,Below code helps you for resolving the issue,i am using below code in java.You can use any other language also.
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With,accept,Origin");
Related
I used postman to test my web service. In the http response body, I find the WS's response.
When I test my call, in my web application, using ajax, I can not find the response anymore. The tab contains a message saying "This request has no response data available."
this is my ajax call:
$.ajax({
url: url,
method: "POST",
data: params,
success:function(response) {
console.log(response); // no console here!
console.log('response');
},
error:function(){
console.log("error");
}
});
Hi, Try like this.
In the ajax, you are passing params, it should contain something like action = get_pincodes.
while handling this, action = get_pincodes.
you must write echo json_encode($responce);exit;
EX:
if($_REQUEST['action'] != "" && $_REQUEST['action'] == 'get_pincodes'){
$responce = array();
$responce[] = "500113";
$responce[] = "500114"; // etc....
echo json_encode($responce);exit;
}
maybe Adding charset=utf-8 to Content-Type in the response headers could solve the issue : Content-Type: application/json; charset=utf-8
$.ajax({
url: url,
method: "POST",
dataType: "json",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json;charset=utf-8'
},
data: params,
success:function(response) {
console.log(response); // no console here!
console.log('response');
},
error:function(){
console.log("error");
}
});
try to check if the XHR filter is selected and dont forget to reload the page afterwards
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!
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.
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"])
}
I am trying to complete a GET request using $http instead of ajax. The call works perfectly with ajax, but when I try to do the same thing with $http I get a 400 (Bad Request) error. I believe I am following the Angular documentation correctly. Any ideas? Hopefully this will also be helpful for others experiencing the same issue.
The ajax code that works:
$.ajax({
type: "GET",
accept: 'application/json',
url: myURL,
headers: {"Authorization": "Basic " + basicKey},
dataType: "json",
contentType: 'application/x-www-form-urlencoded',
data: requestPayload,
async: false
}).done(function(serverData) {
console.log(serverData.access_token);
}).fail(function(error) {
console.log(error);
});
The $http code that does not work:
var basicConfig = {
method: 'GET',
url: myURL,
headers: {
'Authorization': 'Basic ' + basicKey,
'Accept': "application/json",
'Content-Type': 'application/x-www-form-urlencoded'
},
data: requestPayload
}
$http(basicConfig).success(function(data, status){
console.log(status);
}).error(function(data, status){
console.log(status);
});
Thanks in advance.
use params instead of data. data is the request body, used for POST requests, whereas params is for query string variables in GET requests.