How can handle session state in angularJS with json api auth - javascript

I want to create a new post from mobile app using wp-rest api, in order to do this I have to logged in with a form; well, the authentication with json api auth works well I submit username and password and I enter; but, when I try to create a new post with wp-rest api I have this error :"You don't have permission to do this." It seems that I'm not logged in but I'm !!!
my code is this :
var data={"title":"Hello World!","content_raw":"Content","excerpt_raw":"Excerpt"};
$scope.register = function() {
$http({
method: 'POST',
url: 'http://url.com/provawp/wp-json/wp/v2/posts',
data: data,
headers: {'Content-Type': 'application/json'}
})
.success(function(data, status, headers, config) {
alert("Città aggiunta correttamente!");
})
.error(function(data, status, headers, config) {
}).
catch(function (error) {
alert("Erroreee!");
console.log("error : " + JSON.stringify(error) );
});
}

If you are using web tokens. You can put your token inside your http header by creating http interceptors

and also you use like this:
$http({
method: 'POST',
url: 'http://url.com/provawp/wp-json/wp/v2/posts',
data: data,
headers: {
'Content-Type': 'application/json',
'Authorization' : 'bearer Dfdsf54sdff#dfsdsfFF'
}
})
you contact you back end developer for this situation:
bearer and any other
Dfdsf54sdff#dfsdsfFF your Authorization token

Related

How to make a HTTP post request like a HTML form using Axios?

I am trying to connect to an API (nova.astrometry.net) that requires an HTTP post request just like a form (x-www-form-encoded). I am using Axios for that, but still, I am getting this error as a response from the API { status: 'error', errormessage: 'no json' }
Here's the code for reference
axios({
method: 'post',
url: 'http://nova.astrometry.net/api/login',
data: {
'request-json': JSON.stringify({ "apikey": process.env.API_KEY })
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
}).then((response) => {
console.log(response.data)
});
I also tried using the request library but got the same response.
The content type required by the api is 'application/x-www-form-urlencoded' but you are sending 'application/json'.
To send that data, do the following:
const body = new URLSearchParams();
body.append('request-json', JSON.stringify({ "apikey": process.env.API_KEY }));
Then use the above body in the body field of axios.
axios.post('http://nova.astrometry.net/api/login', body, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(res => console.log(res.body))
.catch(console.error);

How to use $scope value from one HTTP request in another HTTP request

I am using AngularJS to send form data to the server.
app.controller("OrganizerReg", ["$scope","$http", function($scope,$http) {
$scope.userOrganizer = {};
$scope.processform = function() {
$http ({
method: 'POST',
url: 'http://52.11.67.77:3000/api/users',
headers: {'Content-Type': 'application/json'},
data: JSON.stringify($scope.userOrganizer)
})
.success(function(response) {
console.log(response.user_id);
$scope.user_id = response.user_id;
})
$http ({
method: 'POST',
url : 'http://52.11.67.77:3000/api/users/'+$scope.user_id+'/accessTokens',
})
.success(function(response) {
console.log(response);
})
}
In order to get access Token , I need to send a POST request.The response from first HTTP request , gives the user_id which is needed for generating the access token. The problem is whenever I send the request, the $scope.user_id returns undefined in the header. How to set my $scope.user_id global, so that it can be used by another HTTP request.
EDIT
I read the duplicate question but it still hasn't helped me.
use promise chains to call the request after another
function firstReq(){
return $http({
method: 'POST',
url: 'http://52.11.67.77:3000/api/users',
headers: {'Content-Type': 'application/json'},
data: JSON.stringify($scope.userOrganizer)
})
}
function secondReq(){
return $http({
method: 'POST',
url : 'http://52.11.67.77:3000/api/users/' +$scope.user_id + '/accessTokens',
})
}
$scope.processform = function() {
firstReq()
.then( function( response )
{
console.log(response.data.user_id);
$scope.user_id = response.data.user_id;
return secondReq();
})
.then(function(response){
console.log(response.data);
})
}

pass Variable to Restful

my question is: How can i pass variable(java script) to a rest apllication
This one of my functions in my controller.js:
This code sampel work, but i cant use my var email and password.
at the moment i use the url path log me in(url : 'rest/ab/einloggen/t#rt.de/22'). But how can i use var email(t#rt.de) and passwort(22).
app.controller('loginCtrl', function($scope, $location,$http){
$scope.submit = function(){
var email = $scope.username;
var password = $scope.password;
$http({
method : 'GET',
url : 'rest/ab/einloggen/t#rt.de/22'
}).success(function(data, status, headers, config) {
console.log(data);
if(data=="true"){
$location.path('/eingeloggt');
console.log("lalala");
}
}).error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
};
});
Here is the login rest function:
#Path("/einloggen/{username}/{passwort}")
#GET
public String einloggen(#PathParam("username") String Username,#PathParam("passwort") String Passwort)
{
// Bekomme die strings
Business b = new Business();
boolean test =b.einloggen(Username, Passwort);
//Return einer JSON
String ersatzBool ="false";
if(test==true){
ersatzBool="true";
}
return ersatzBool;
}
if you want to pass data to webapi you can use
'POST' instead of 'GET', In the below example I have passed json data {id: 2 }
and getting response as a list of products, In the api post method id 2 is available.
$http.post('http://localhost:1011/productDetails', { Id: 12 }, {
headers: {
'Content-MD5': '917200022538',
'Accept': 'application/Json',
'Content-Type': 'application/Json'
}
}).then(onUserComplete, onError);
var onUserComplete = function (response) {
$scope.Products = response.data;
};
var onError = function (reason) {
$scope.error = "Error while fetching records.";
};
This is something I had to do while communicating with a server(CMS application - Contentstack) using Restful api's, one striking difference would be I had to use authtoken.
$http({
url: siteUrl,
method: methode,
headers: {
access_token: auth_token,
api_key: site_api_key,
Accept: data_type, // --> 'application/json, text/plain, */*'
},
data: dataBody
}).then(function (resp) {
console.log('success ', resp);
callback(resp);
}, function(err){
console.log(err, "error");
});

Http post returns no respose and there is no error in the request in angular js?

i am given a task to create basic CRUD app.
I am trying to insert a text using http post, but there is no data in the success method.
$http({
url: url,
method: "POST",
dataType: 'json',
data: {
Id: '201414',
Note: 'sample',
},
headers: { 'Content-Type': 'application/json; charset=UTF-8' }
})
. success(function(response) {
console.log(response); //Returns Empty
} );
what am i doing wrong?
If the server method should return a value but doesn't, probably an error occurred server-side. This error however is not passed as an argument to the success handler and doesn't throw an error in the request.
You can find out if an error occurred by attaching an error handler to the $http call.
Try the following:
$http({
url: url,
method: 'POST',
data: {
Id: '201414',
Note: 'sample'
}
})
.success((data, status, headers, config) {
console.log(status);
})
.error(function(data, status, headers, config) {
console.log(data);
});

how to pass authtoken via header using angular js

I am trying to pass my api authtoken via the header. I am new to angular js so i am not able to do that. My code:
$scope.init=function(authtoken,cityname){
$scope.authtoken=authtoken;
$scope.cityname=cityname;
$http({method: 'GET', url: '/api/v1/asas?city='+$scope.cityname+'&auth='+$scope.authtoken}).success(function(data) {
Right now I am passing the authtoken in the api url. But I want to pass the token via the header.
usually you pass auth token in headers. Here is how i did it for one of my apps
angular.module('app', []).run(function($http) {
$http.defaults.headers.common.Authorization = token;
});
this will add auth token to headers by default so that you wont have to include is every time you make a request. If you want to include it in every call then it will be something like this
$http({
method: 'GET',
url: '/api/v1/asas?city='+$scope.cityname,
headers:{
'Authorization': $scope.authtoken
}
}).success(function(data) {
//success response.
}).error(function(error){
//failed response.
});
You can configure on application run
youapp.run(function($http) {
$http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'
});
or pass it throw each request
$http({
url:'url',
headers:{
Authorization : 'Basic YmVlcDpib29w'
}
})
Angular $Http reference

Categories