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.
Related
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 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");
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 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.
Here I have two for me the same request: jquery ajax and XMLHttpRequest but JQ ajax dont work... SO want to know what is the difference:
JQ ajax:
var urlAjax = "http://www.agroagro.com/v1/register";
$.ajax({
type: "POST",
url: urlAjax,
contentType: "application/x-www-form-urlencoded",
data: {
name: "Mile3",
email: "new1#new.com",
password: "face1book"
},
crossDomain:true,
success: function(data) { console.log(data); },
error: function(data) {console.log(data); },
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
},
headers: {
'Access-Control-Allow-Origin': '*'
}
});
});
});
and this ajax request dont work... give me 404 error...
XMLHttpRequest:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {"done"}
}
xhr.open("POST","http://agroagro.com/v1/register",true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send("name=Henry&email=Ford#ford.com&password=1234");
This request work fine, but I need to know what is the difference, the both call POST url...
Also what I need to change in my JQ ajax request to work?
Access-Control-Allow-Origin is a response header so it shouldn't be on the list of request headers: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#The_HTTP_response_headers
Remove the following:
beforeSend: function (xhr) {
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
}
and
headers: {
'Access-Control-Allow-Origin': '*'
}