How to set headers in Ajax call? - javascript

I am developing multi-language website using Angularjs and a Web api as backend. I am trying to send RequestedPlatform and RequestedLanguage in the header whenever I make an API call.
Below is my Ajax request call.
$http.post(url,RegistrationData).then(function (response) {
var pageList = response.data.ID;
toastr.success('', 'Registered Succesfully');
$state.go('Registration.OTPVerification', { pageList });
}, function (error) {
toastr.error('', 'Error Occured');
});
updated code
var RegistrationData = {
FirstName: $scope.user.Fname,
LastName: $scope.user.Lname,
Password: $scope.user.password,
Gender: "Male",
DateOfBirth: "2017-04-04",
Nationality: $scope.user.selectedGlobe,
Mobile_CountryCod: "91",
MobileNumber: $scope.user.mobilenumber,
EmailId: $scope.user.email,
Home_Location: $scope.user.homeLocation,
Home_City: $scope.user.homeCity,
Home_Neighbourhood: $scope.user.homeNeighbourhood,
Home_HouseNumber: $scope.user.housenumber,
Home_MainStreet: $scope.user.homemainstreet,
Home_SubStreet: $scope.user.homesubstreet,
Work_Location: $scope.user.worklocation,
Work_City: $scope.user.workcity,
Work_Neighbourhood: $scope.user.workNeighbourhood,
Work_HouseNumber: $scope.user.workhousenumber,
Work_MainStreet: $scope.user.workmainstreet,
Work_SubStreet: $scope.user.worksubstreet
};
var req = {
method: 'POST',
url: url,
data: { RegistrationData: RegistrationData },
headers: {
RequestedPlatform: "Web",
RequestedLanguage: "English"
}
}
$http(req).then(function (response) {
var pageList = response.data.ID;
toastr.success('', 'Registered Succesfully');
$state.go('Registration.OTPVerification', { pageList });
}, function () {
toastr.error('', 'Error Occured');
});
May I get some help to set headers in Ajax. Any help would be appreciated.

you can send headers with headers property of $http
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': undefined
},
data: { test: 'test' }
}
$http(req).then(function(){...}, function(){...});
and if you want headers for all the requests that can be fully configured by accessing the $httpProvider.defaults.headers configuration object,
Reference

There are few ways and I have posted one which I have been using it for a while. I hope you are looking for the below
$http.post('test', data, {
withCredentials : false,
transformRequest : angular.identity,
headers : {
'Content-Type' : undefined
}
})

Related

Vue-Cookies .set function isn't setting a cookie

Vue-Cookies .set function doesn't seem to set the cookie in Chrome, Safari or Firefox. Below is the code I'm using, called whenever someone authenticates:
vm.$cookies.set('token', response.headers.authorization)
Where "response.headers.authorization" is a real variable fetched from response data.
I get no errors in the console and I am able to see the site's cookies using the .keys function.
Does anyone have any ideas? I've posted a bigger block below to give some context.
export default {
name: 'Home',
components: {},
methods: {
sso: function () {
var vm = this;
axios({
method: 'POST',
url: api + 'secure/use',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
data: {
username: vm.$refs.username.value,
password: vm.$refs.password.value
}
}).then(function (response) {
vm.response = response.data;
if (response.headers.authorization) {
console.log(vm.$cookies.keys()) //THIS WORKS.
vm.$cookies.set('token', response.headers.authorization) //THIS HAS NO EFFECT.
vm.$router.push('/')
} else {
vm.error = true;
}
})
}
}...

React axios data type issue

I have the following submit method:
submitForm(e) {
e.preventDefault();
var token = document.getElementsByTagName("meta")[0].getAttribute("content");
var form = document.querySelector('.form');
if(navigator.onLine && JSON.parse(localStorage.getItem('candidates'))) {
axios({
url: '/save-data',
method: 'POST',
contentType: 'application/json',
data: {
"candidates": localStorage.getItem('candidates')
},
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': token
}
}).then(function(response) {
console.log(response);
})
.catch(function(e){
console.log(e);
});
}
else {
var singleCandidate = serialize(form, { hash: true });
var fromStorage = localStorage.getItem("candidates");
if (fromStorage) {
var parsedFromStorage = JSON.parse(fromStorage)
parsedFromStorage.push(singleCandidate)
localStorage.setItem("candidates", JSON.stringify(parsedFromStorage));
}
else {
localStorage.setItem("candidates", JSON.stringify([singleCandidate]));
}
}
}
it loads data from local storage and submits it if there is data and connection at the same time.
However there is something that doesn't work with the following:
data: {
"candidates": localStorage.getItem('candidates')
},
if I do:
data: {
"candidates": [
{
"name": this.state.firstName,
"email": this.state.email,
"university": this.state.university,
"degree": this.state.degree
}
]
},
I get a positive response, form data gets submitted. However I have to submit this value (localStorage.getItem('candidates')) and when I do that I get the following:
Should "localStorage.getItem('candidates')" be changed to another format?

AngularJS - $http missed specific key from request Payload

I'm using angular 1.5.7, and no idea why It's missing that key. Frequency of that bug is really low.
Server side rarely get post Request Payload without "priceMin":
expected:
{priceMin: 0, priceMax: 964, category: "", name: ""}
what I've get:
{priceMax: 964, category: "", name: ""}
function _doRequestPOST(request_url, data) {
var def = $q.defer(),
request = {
headers: {
'X-Requested-With' :'XMLHttpRequest'
},
method : 'POST',
url : request_url,
data : data
};
http = $http(request).then(
function(response){
//success
def.resolve(response);
},
function(response){
//error
def.reject(response);
}
);
delete http;
return def.promise;
};
this.sendStats = function(){
var requestData = {
priceMin: self.priceRange.min,
priceMax: self.priceRange.max,
category: self.filterExterior,
name: self.searchBot.name
};
_doRequestPOST('/saveFilterData', requestData);
}
};

XSRF with AngularJS: DocuSign API Embedded View Client-Side implementation

I have an AngularJS application that is utilizing the DocuSign Embedded Signing REST API to open a tab with the embedded document to DocuSign after the user completes a form.
I have looked around StackOverflow on some topics to help, but I can't find anything like my implementation.
I continue to get a 401 error on login, and I'm pretty sure it's because of CORS being blocked.
Any help is appreciated!
Here is my DocuSign factory:
app.factory('dsFactory', function($http) {
return {
login: function(templateId) {
return $http({
url: 'https://demo.docusign.net/restapi/v2/login_information',
method: 'GET',
params: {
'X-DocuSign-Authentication': {
'DocuSignCredentials': {
'UserName': 'xxx',
'Password': 'xxx',
'IntegratorKey': 'xxx'
}
}
}
});
},
envelope: function(baseUrl, templateId, recipientName, templateRoleName) {
var url = baseUrl + "/envelopes";
return $http({
url: url,
method: 'POST',
params: {
"emailSubject": "DocuSign API call - Embedded Sending Test",
"templateId": templateId,
"templateRoles": [{
"email": "xxx",
"name": recipientName,
"roleName": templateRoleName
}],
"status": "sent"
}
});
},
getUrl: function(baseUrl, envelopeId, recipientName) {
var url = baseUrl + "/envelopes/" + envelopeId + "/views/recipient";
return $http({
url: url,
method: 'POST',
params: {
"returnUrl": "http://www.docusign.com/devcenter",
"authenticationMethod": "email",
"email": "xxx",
"userName": recipientName
}
});
}
};
});
And here is the promise chain to open a new tab with the embedded document view:
// Elaborate promise chain for DocuSign login and document url retrieval
loginPromise = dsFactory.login($scope.templateId);
loginPromise.then(
function(payload) {
$scope.dsBaseUrl = payload.data.loginAccounts[0].baseUrl;
envelopePromise = dsFactory.envelope($scope.dsBaseUrl, $scope.templateId, $scope.businessName, 'Signer');
envelopePromise.then(
function(payload) {
$scope.dsEnvelopeId = payload.data.envelopeId;
urlPromise = dsFactory.getUrl($scope.dsBaseUrl, $scope.dsEnvelopeId, $scope.businessName);
urlPromise.then(
function(payload) {
$scope.dsCompleteUrl = payload.data.returnUrl;
window.open($scope.dsCompleteUrl);
},
function(errorPayload) {
console.log('retrieve DS url failed' + '\n');
console.log('Status: ' + errorPayload.status);
}
);
},
function(errorPayload) {
console.log('retrieve DS envelopeId failed' + '\n');
console.log('Status: ' + errorPayload.status);
}
);
},
function(errorPayload) {
console.log('DS login failed' + '\n');
console.log('Status: ' + errorPayload.status);
}
);
Any thoughts or assistance on how I can get this integration working?
Maybe something to do with the headers?
This issue is not specific to Angular.
If you can either use callback or ask target domain to add your domain in the "Access-Control-Allow-Origin" header. For your specific issue, I don't think you can ask DocuSign to do this. It leaves you with #2.
You can call the API from server side.
Angularjs https (browser)->your server->DocuSign API>your server->browser

How to post data with angular js to sql server

Thanks for all your input, but now I have more or less a similar problem, I have the data that needs to be stored in sql-server database, when I try to post it the data does not get written. Is my code structure correct?
self.CurrentDowntimeEvent = {
method: 'POST'
, url: 'someurl/test'
, data: {
DepartmentId: cookie
, CategoryId: -1
, Comment: ""
, DowntimeStart: "2014-07-07T10:00:00"
, DowntimeEnd: null
}
, headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
}).success(function (data) {
console.log(data);
}).error(function (data) {
});
$http is a service which should be injected into the controller, so you shouldn't need self. to reference it:
self.RecordsSave = function () {
for (var i = 0; i < self.Employees.length; i++) {
var employee = self.Employees[i];
var params = {
CompanyNumber: employee.ClockNumber,
Department: employee.DepartmentID,
Present: employee.Present,
Reason: employee.AbsentCode
};
$http.post(SAVE_EMPLOYEERECORDS, {
params: params
}).success(function (data) {
alert("testing");
});
}
};

Categories