I am using ModelViewSet to fetch objects from my database and rendering them in a Django template. Since JWT Authentication is needed, I am sending the token in the header of AJAX request. I get the response back but if I redirect to the correct page I get a 401 Unauthorised.
$.ajaxSetup({
headers: {
'Authorization': "Bearer " + window.sessionStorage.getItem("token")
}
});
$(document).ready(function () {
$("#id").on('click', function (event) {
event.preventDefault()
var url = "myurl"
$.ajax({
url: url,
type: 'GET',
dataType: "html",
tokenFlag: true,
success: function(res) {
location.href = url
}
});
});
});
I want the page to redirect and the template rendered. It works fine in Insomnia.
Related
I am submitting a form using ajax with enabling CSRF protection to true in config.php. First time, the form is submitting well but second time it's showing error "Forbidden. The Action you requested is not allowed. 403". How can I securely submit form using ajax by enabling CSRF protection to true.
Below is the ajax function I am using.
$('#loginfrmbtn').on('click', function(){
$(this).prop('disabled', true);
var formdata=$('#loginfrm').serialize();
$.ajax({
type: 'POST',
data: formdata,
url: '<?php echo base_url('logincheck');?>',
dataType: 'json',
success: function(res){
$('#loginfrmbtn').prop('disabled', false);
console.log(res);
}, error: function(jqXHR){
console.log(jqXHR);
}
})
})
Try to use the headers option of the jQuery ajax function (https://api.jquery.com/jquery.ajax/) to send the csrf token within each request like so:
$.ajax({
...
headers:{
'X-CSRF-TOKEN': $( 'input[id="csrf_tsecurity"]' ).val(),
},
...
});
And the following codeigniter config:
public $CSRFTokenName = 'csrf_tsecurity';
public $CSRFHeaderName = 'X-CSRF-TOKEN';
public $CSRFRegenerate = false;
I've checked the gizillion answers to this question and for some reason I can't get this to work.
I get the error:
401 (Unauthorized)
My route is an api route guarded.
My data:
let ajaxMainTemplate = {
'mainTemplate': mainTemplate,
'templateId': templateId,
'_token': accessToken,
}
My ajax call:
$.ajax({
type: 'POST',
url:`../api/aiMainTemplate/${ajaxData.templateId}`,
data: {
_token: ajaxData._token,
ajaxData
},
success: function(response) {
console.log(response)
}
})
I've tried the above to test based on another response. I put the token outside of the ajaxData object. I get the same error. I've also attempted:
$.ajax({
type: 'POST',
url:`../api/aiMainTemplate/${ajaxData.templateId}`,
headers: { 'X-CSRF-TOKEN': ajaxData._token },
data: ajaxData,
success: function(response) {
console.log(response)
}
})
Same.
I've also confirmed the token is there by adding a console.log Any ideas what I'm doing wrong with this?
My url was behind the api protected route so I had to do an ajax call to login into it via ajax.
The credentials are in a variable ajaxData.
$.ajax({
type: 'POST',
url: 'http://127.0.0.1:8000/api/login',
data: ajaxData,
success: function(response) {
shopifyToken = response.success.token;
getListProducts(shopifyToken);
}
});
With the shopify token generated from this login it worked.
I'm trying to add header to request in Ajax with JQuery.
Below is the code :-
$.ajax({
type: "POST",
contentType: "application/json",
url: "http://localhost:8080/core-service/services/v1.0/patients/registerPatients",
data: JSON.stringify(patientDTO),
//crossDomain : true,
dataType: 'json',
headers: {"X-AUTH-TOKEN" : tokken},
success: function(patientDTO) {
console.log("SUCCESS: ", patientDTO);
/* location.href = "fieldagentHRA.html";*/
if (typeof(Storage) !== "undefined") {
localStorage.setItem("patUrn", patientDTO.data);
location.href="fieldagentHRA.html";
}
},
error: function(e) {
console.log("ERROR: ", e);
display(e);
},
done: function(e) {
enableRegisterButton(true);
}
});
I inspected this with chrome and found that header's body is not being added.
Then I used Requestly (Requestly is chrome+firefox plugin with which we can manually add a header to the request).
After manually adding header :-
In both the pics request header x-auth-token is present in "ACCESS-CONTROL-REQUEST-HEADERS" but "X-AUTH-TOKEN" header along with header value is present in second pic which is not there in the first pic.
So my question is how to add request headers in Ajax with JQuery ?
There are couple of solutions depending on what you want to do
If want to add a custom header (or set of headers) to an individual request then just add the headers property and this will help you to send your request with headers.
// Request with custom header
$.ajax({
url: 'foo/bar',
headers: { 'x-my-custom-header': 'some value' }
});
If want to add a default header (or set of headers) to every request then use $.ajaxSetup(): this will help you to add headers.
//Setup headers here and than call ajax
$.ajaxSetup({
headers: { 'x-my-custom-header': 'some value' }
});
// Sends your ajax
$.ajax({ url: 'foo/bar' });
add a header (or set of headers) to every request then use the beforeSend hook with $.ajaxSetup():
//Hook your headers here and set it with before send function.
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('x-my-custom-header', 'some value');
}
});
// Sends your ajax
$.ajax({ url: 'foo/bar' });
Reference Link : AjaxSetup
Reference Link : AjaxHeaders
I making an AJAX request to the food2fork api and can't get by the No 'Access-Control-Allow-Origin' header is present error. I've tried setting the header in beforeSend and setting crossDomain: true but it didn't work.
This is my AJAX call:
$.ajax({
type: "GET",
dataType: 'json',
url: url,
crossDomain: true,
beforeSend: function(xhr) {
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
},
success: function(data){
console.log('in ajax json call');
console.log(data);
$('#info').html(JSON.stringify(data));
}
});
I tried setting the request header server side in node express.js with:
router.get('/test', cors(), function(req,res)
{
res.set("Access-Control-Allow-Origin", "*"); //set header here
res.render('exampleSearch', {title: 'FM | Test'});
});
Cors is an npm package that sets cross-reference permissions but didn't help me solve the problem.
Can you tell me what I'm doing wrong?
Client-side request doesn't work in this case. I had to do the request server side:
router.post('/test', function(req,res){
var callback = function(response){
var str = '';
//another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
});
//the whole response has been recieved
response.on('end', function () {
var recipes = JSON.parse(str);
//do something with recipes
});
}
var options = {
host: "food2fork.com",
path: "/api/search?key=[myKey]&q=" + ingredients
};
http.request(options,callback).end();
});
Used code from nodejitsu.com
We are new to angular js.
We tried http request using $http.get it is working fine. But in post request it is creating an issue, it comes to success and show bad parameter error code 103.
Same we have tried in ajax request using $.ajax({}), and it is working fine.
I have also paste my code.
Can anyone help us out?
mainApp.controller('registrationCtrl', function($scope, $location, $http) {
$scope.registration = function() {
console.log("registration called");
var ws_url = "http://apparelinindia.com/selfiestandoff/WebServices/register";
var request = $http({
method: "post",
url: ws_url,
data: {
user_email: $scope.email,
user_password: $scope.password
},
dataType: 'json',
headers: {
'Content-Type': 'application/json'
}
});
request.success(function(data) {
console.log("Success" + data);
});
request.error(function(error) {
console.log("Success" + JSON.stringify(error));
});
};
});
You can use http Post in following way:
var request = $http.post(ws_url, {
user_email: $scope.email,
user_password: $scope.password
});
The name of the http method should be written in uppercase. Also, the property datatype is not awaited by $http, you should remove it:
var request = $http({
method: "POST",
url: ws_url,
data: {
user_email: $scope.email,
user_password: $scope.password
},
headers: {
'Content-Type': 'application/json'
}
});
Note, in the above call to $http you are setting the header 'Content-Type': 'application/json'. But this header is automatically injected by $http (see $http documentation), therefore you can remove it, and use the short syntax:
var request = $http.post(ws_url, data);
with data equals to:
{
user_email: $scope.email,
user_password: $scope.password
}
Are You Getting this error ??
{"status":false,"error":{"code":"103","message":"Required Parameters not found"}}
If Yes, Its Not your Problem Contact the Web service provider.
Ask him to give the valid parameter