how to add user to openfire by angularjs $http using OF RestApi? - angularjs

I am using OpenFire Rest APi v 1.2.3 to add new members to it. this is my code to send my request.
var par ={
username:$scope.currentItem.tel1,
password:buildKey($scope.currentItem.password),
name:$scope.currentItem.name,
email: $scope.currentItem.email
};
$http({
method: "POST",
url: baseCfg.xmpp_server + "users",
headers: {
"Content-Type": "application/json",
"Authorization":"Basic YWRtaW46IVFBWjFxYXo="
},
data:JSON.stringify(par)
}).then(function () {
console.log("done");
}, function () {
console.log("error");
});
but I am getting this response :
OPTIONS 403 forbidden
and in request headers there is no headers and parameters.

it was my silly mistake witch i donot turn off my restapi.
i must go to this path an enable it:
OpenFire admin panel > server > server settings > and check Enable

Related

CORS post call not working in Angularjs

I am trying to implement cross-origin post call from angularjs application, then I get the following error.
Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.
But, when I make a Ajax call it works properly.
How HTTP post call work in angularjs?
Ajax call
$.ajax({
type: 'POST',
url: getAccessTokenUrl,
data: JSON.stringify(clintdata),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(resultData) {
console.log(resultData);
},
error: function (request, status, error) {
console.log(status);
}
});
Angularjs HTTP call
$http({
method: 'POST',
url: getAccessTokenUrl,
data: clientdata,
headers: {
'Authorization': undefined,
'Auth-Token': undefined
}
}).then(function(res){
console.log(res);
}, function(err){
console.log(err);
});
I have some default setting. Authorization is for others REST
$http.defaults.headers.common['Content-Type'] = 'application/json;charset=utf-8;' ;
$http.defaults.headers.common['Auth-Token'] = 'X-Requested-With';
$http.defaults.headers.common['Authorization'] = $('#Authorization').val();
Access-Control-* headers are response headers. They come from the server in response to a request. You do not apply them to your request headers.
If your jQuery request works correctly without adding any additional headers, then your AngularJS request should work the same.
The equivalent jQuery request in AngularJS (including removing the Authorization and Auth-Token headers you've set via defaults) is
$http.post(getAccessTokenUrl, clientdata, {
headers: {
Authorization: undefined,
'Auth-Token': undefined
}
}).then(response => {
console.log(response.data)
})
or the long version
$http({
method: 'POST',
url: getAccessTokenUrl,
data: clientdata,
headers: {
Authorization: undefined,
'Auth-Token': undefined
}
}).then(...)
AngularJS by default...
POSTS requests as application/json content-type
Serializes the data property to JSON
Expects a JSON response
Resolves the $http promise with a response object with the response body parsed as JSON into the data property
Remove the following setting
$http.defaults.headers.common['Auth-Token'] = 'X-Requested-With';
$http.defaults.headers.common['Authorization'] = $('#Authorization').val();
Add Authorization header dynamically from Interceptor
request: function(config) {
if (angular.isUndefined(config.skipInterceptor) || !config.skipInterceptor) {
// add Authorization token
}
return config;
}
Http call like this
$http.post('your url', {
skipInterceptor: true
})

restdb.io wont let me access with GET verb although I got CORS enabled

I have CORS enabled in restdb.io. I have set up so all origins are allowed to make GET requests. I have generated a Api key .This is the error message and api call. The wierd thing is that if I click the request in the network tab in chrome dev mode I can see it got 200 ok from the server. Am I missing something?
No 'Access-Control-Allow-Origin' header is present on the requested resource.
I am using Angular JS.
function getImages() {
var def = $q.defer();
$http({
async: true,
crossDomain: true,
url: getImagesURL,
method: "GET",
headers: {
"content-type": "application/json",
"x-apikey": APIKEY,
"cache-control": "no-cache"
}
}).then(function successCallback(response) {
def.resolve(response.data);
}, function errorCallback(response) {
console.log("Error " + response.data)
});
return def.promise;
}
Solved it. I was using the wrong api key.

How to handle CORS requests in AngularJS

I'm facing problem with CORS requests in AngularJS while calling web services but the same service able to call by using jQuery.
Note: From server side we are receiving header "Access-Control-Allow-Origin:*" and these services are running fine in jQuery application.
Here I'm posting my AngularJS code as well as jQuery code.
AngularJS:
$http({
method: 'POST',
url: $rootScope.host + "UserLogin",
//headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: {
"uname": $scope.uname,
"password": $scope.password
},
}).then(function (success) {
$scope.loginDetails = success;
console.log($scope.loginDetails);
}),function (error){
console.log(error);
});
If I pass the header like headers: { 'Content-Type': 'application/x-www-form-urlencoded' } able to ping the service but my request is not going in JSON format.
If I change the header to 'Content-Type': 'application/json', getting
XMLHttpRequest cannot load https://XXXX.XXXX.in/XXXXAPI/UserLogin.
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://170.11.0.61' is therefore not allowed access.
I don't know what is the reason for this error.
$.ajax({
url: BASE_URL + "UserLogin",
type: "POST",
xhrFields: {withCredentials: true},
data: {
"uname": uname,
"password": password
},
cache: false,
success: function (result, textStatus, request) {
console.log(result);
},
error: function (e) {
console.log("Error in login service call:"+JSON.stringify(e));
}
});
This jQuery is sending my request in the json format.
Try to pass headers like
headers: { 'Content-Type': 'application/json' }

AngularJS http request to postmark it returns this -> "data":null,"status":-1

When I send request to postmark using http in angular it returns null.
I am trying to use angular to send email using postmark restful api, did I missed something, or is there any other way to send email using angular and postmark?
Anyway here's my code:
var data = {
From : 'test#gmail.com',
ReplyTo : 'test#gmail.com',
To : 'test#gmail.com',
subject : 'Test Email Subject',
HtmlBody : '<html><body><p style="color: red">Test</p></body></html>'
};
var app = angular.module('myApp', []);
app.controller('myCtrl', function($http){
$http({
method: 'POST',
url: 'https://api.postmarkapp.com/email',
data: JSON.stringify(data),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-Postmark-Server-Token': '*************'
}
}).then(function successCallback(response) {
alert('success');
}, function errorCallback(response) {
alert(JSON.stringify(response));
});
});
I work on Postmark.
I don't have a lot of experience with Angular, but if I understand correctly, you're initiating an AJAX request from the client-side.
For your security, Postmark doesn't allow CORS requests, so in order to send an email to postmark, you'll need to proxy the request through an endpoint in your backend.
If you contact support, we'll be happy to provide code snippets to do this in your language of choice where possible.

Nodejs sending external API POST request

i am trying to send a POST request from my angularjs controller to the nodejs server which should then send a full POST request to the external API and this way avoid CORS request as well as make it more secure as i'm sending relatively private data in this POST request.
My angularjs controller function for making the post request to the nodejs server looks like this and it works fine:
var noteData = {
"id":accountNumber,
"notes":[
{
"lId":707414,
"oId":1369944,
"nId":4154191,
"price":23.84
}
]
}
var req = {
method: 'POST',
url: '/note',
data: noteData
}
$http(req).then(function(data){
console.log(data);
});
Now the problem lies in my nodejs server where i just can't seem to figure out how to properly send a POST request with custom headers and pass a JSON data variable..
i've trierd using the nodejs https function since the url i need to access is an https one and not http ,i've also tried the request function with no luck.
I know that the url and data i'm sending is correct since when i plug them into Postman it returns what i expect it to return.
Here are my different attempts on nodejs server:
The data from angularjs request is parsed and retrieved correctly using body-parser
Attempt Using Request:
app.post('/buyNote', function (req, res) {
var options = {
url: 'https://api.lendingclub.com/api/investor/v1/accounts/' + accountNumber + '/trades/buy/',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': apiKey
},
data = JSON.stringify(req.body);
};
request(options, function (error, response, body) {
if (!error) {
// Print out the response body
// console.log(body)
console.log(response.statusCode);
res.sendStatus(200);
} else {
console.log(error);
}
})
This returns status code 500 for some reason, it's sending the data wrongly and hence why the server error...
Using https
var options = {
url: 'https://api.lendingclub.com/api/investor/v1/accounts/' + accountNumber + '/trades/buy/',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': apiKey
}
};
var data = JSON.stringify(req.body);
var req = https.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
res.on('end', () => {
console.log('No more data in response.');
});
});
req.on('error', (e) => {
console.log(`problem with request: ${e.message}`);
});
req.write(data);
req.end();
Https attempt return a 301 status for some reasons...
Using the same data, headers and the url in Postman returns a successful response 200 with the data i need...
I don't understand how i can make a simple http request...
Please note: this is my first project working with nodejs and angular, i would know how to implement something like this in php or java easily, but this is boggling me..
So after a lot of messing around and trying different things i have finally found the solution that performs well and does exactly what i need without over complicating things:
Using the module called request-promise is what did the trick. Here's the code that i used for it:
const request = require('request-promise');
const options = {
method: 'POST',
uri: 'https://requestedAPIsource.com/api',
body: req.body,
json: true,
headers: {
'Content-Type': 'application/json',
'Authorization': 'bwejjr33333333333'
}
}
request(options).then(function (response){
res.status(200).json(response);
})
.catch(function (err) {
console.log(err);
})

Resources