Ionic v1 AngularJS $http POST request not working - javascript

I'm trying to send a POST request to a rest API, but I don't seem to able to do it correctly, I don't know if it's the syntax, or what it could be, I've tried many different ways but nothing seems to work. Here's is some pictures of the service being consumed by POSTMAN (everything works fine here).
The Headers
And the body with the response
But then when I try to consume the service via AngularJS, it keeps sending me erros messages, the localhost server even detects that there is a request, because I can see it on the Eclipse's console, but it doesn't run through the debugger with togglebreakpoints and it does with POSTMAN.
This is one of the many attempts to send a $http request
var json = { practiceId: 1 };
$http({
method: "POST",
url: "https://localhost/GetAppointmentTypes",
data: JSON.stringify(json),
headers: {
"Content-Type": "application/json",
"AERONA-AUTH-TOKEN": $window.localStorage['token']
}
})
.success(function(data) {
$ionicPopup.alert({
title: 'WORKING'
});
})
.error(function (errResponse, status) {
if(status == 403){
$ionicPopup.alert({
title: '403'
});
}
});
But then
And here is another attempt
var url = 'https://localhost/GetAppointmentTypes';
var parameter = JSON.stringify({practiceId:1});
var headers = {
"Content-Type": "application/json",
"AERONA-AUTH-TOKEN": $window.localStorage['token']
};
$http.post(url, parameter, headers).then(function(response){
$ionicPopup.alert({
title: 'WORKING'
});
}, function(response){
$ionicPopup.alert({
title: ' NOT WORKING '
});
});
And the response
Note: the $window.localStorage['token'] is working correctly. I have tried so many things I don't even know what I'm doing wrong now, might be a syntax error, but then ERROR 403 wouldn't be showing.
EDITED (ADDED)
And the Response Variable

Related

422 error 'unprocessable entity' when calling API from Chrome extension

I am building a Chrome extension that aims to send information (url, title etc.) from the current page the user is on to a REST API with a Rails backend. The API call works when I test it with Postman but when I send the data through my extension, I receive the 422 (Unprocessable Entity) error.
This file listens for the click in my extension:
function listenClick() {
const button = document.getElementById('send-data');
button.addEventListener('click', () => {
chrome.tabs.executeScript({
file: 'scripts/send-data.js'
});
})
}
listenClick();
This is the send-data.js file:
function fetchData() {
title = document.querySelector('title').innerText;
const url = window.location.href;
return {
title: title,
url: url
}
}
function sendData(data){
const url = 'http://localhost:3000/api/v1/bookmarks';
fetch(url, {
method: 'POST',
headers: {
"Content-Type": "application/json",
"X-User-Email": "test#mail.com",
"X-User-Token": "asdfkljIOJDHalsdfkla"
},
body: JSON.stringify({
"title": `${data.title}`,
"url": `${data.url}`,
})
})
}
sendData(fetchData());
The error occurs on the line starting with 'X-User-Email'. I am using the 'simple_token_authentication' gem to authenticate users, which uses these headers.
Could someone help me to see what I'm missing?
Realized that the problem was with my ruby code and not with the js.file quoted above. Checking the rails logs helped me realize that.
Try changing the content type of the header. header:{ 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8;application/json' }

"How to fix 'Ajax request getting a 419 unknown status" (solved)

I am using laravel homestead. I am making a game that requires credits on the account of which it is played on. I want to make sure that after every play the credits of the user gets updated through an ajax request, however with this ajax request, I get the same error which is PATCH http://gamesite.test/updateBalance/13 419 (unknown status) if I change the data it gets the error: The GET method is not supported for this route. Supported methods: PATCH.
I already tried to change the methods of the ajax request and it is working on other pages.
The ajax request that I made is the following:
$(oMain).on("save_score", function(evt,iMoney) {
if(getParamValue('ctl-arcade') === "true"){
parent.__ctlArcadeSaveScore({score:iMoney});
}
//...ADD YOUR CODE HERE EVENTUALLY
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: 'updateBalance/'+{{ auth()->user()->id }},
type: 'PATCH',
data: {iMoney:iMoney, _method: "PATCH"},
success: function(res) {
}
});
});
I expected that it would update the users credits, instead got the error: "PATCH http://gamesite.test/updateBalance/13 419 (unknown status)"
EDIT:
Route:
Route::patch('/updateBalance/{id}', 'GamesController#updateBalance');
GamesController:
public function updateBalance(User $id) {
$selecteduser = User::find($id)->first();
$this->validate(request(), [
'credit' => 'int'
]);
$selecteduser->credit = request('iMoney');
$selecteduser->save();
}
Found the answer, I needed to add
to the header in the blade.
use HTTP default GET method, this works fine.
$.get (url, {iMoney:iMoney, _method: "PATCH"} , function(){
//success
})

Array is flattened when it's sent through AJAX jQuery request

I have the following endpoint written in Express, using the body-parser middleware.
app.post("/api/poll/new",api.NewPoll);
api.NewPoll = function(req,res){
if(!req.body) return res.status(400).send("MISSING BODY");
console.log(req.body,typeof(req.body));
if(!req.body.name) return res.status(400).send("MISSING NAME");
if(!req.body.options) return res.status(400).send("MISSING OPTIONS");
//rest of the endpoint goes here
};
The data that the endpoint expects looks like this:
{
"name":"Poller",
"options":[
{
"name":"Jojo's Bizarre Adventure",
"desc":"A great show"
},
{
"name":"Bakemonogatari",
"desc":"A real good show"
},
}
When I send this data through Postman, everything works. req.body.options exists and is an array. However, when I do the exact same thing in a jQuery AJAX call, the result is signficantly different:
var payload = {
name:"Poller",
options:g.newPollInfo
//g.newPollInfo contains the same array
}
$.ajax({
method:"POST",
url:"/api/poll/new",
data:payload,
success:function(data){
console.log(data);
},
error:function(req, status, error){
console.log(req,status,error);
}
});
I get a 400 error, reporting missing Options. The printed req.body looks like this:
{ name: 'Poller',
'options[0][name]': 'Jojo'\s Bizarre Adventure',
'options[0][desc]': 'A great show',
'options[1][name]': 'Bakemonogatari',
'options[1][desc]': 'A real good show' } 'object'
I have never had this problem before. The problem is not in express, as a request through Postman using the same data and it works. The only problem I can think of lies in the fact that the request is made from an iframe serviced through a secure connection, but that doesn't make sense.
I have no idea what causes this error.
According to both these questions, the problem is solved specify the header type on the AJAX Request and stringify.
$.ajax({
method:"POST",
url:"/api/poll/new",
data:JSON.stringify(payload),
contentType:"application/json",
success:function(data){
console.log(data);
},
error:function(req, status, error){
console.log(req,status,error);
}
});

CORS error when trying to post message

I have an AngularJS Application I am trying to post a message through. I am successfully able to log the user in, get the access token, and I have ensured I have my domain in the JavaScript Origins within Yammer.
Whenever I try to post a message, however, I get the following error:
The strange thing is when it does the preflight it seems OK but as the error states I can't figure out why it isn't coming back in the CORS header as I have it registered within the Yammer Client area.
Here is the code for posting:
$scope.YammerPost = function (Yammer) {
var _token = Yammer.access_token.token;
var config = {
headers: {
'Authorization': 'Bearer ' + _token
}
};
$http.post('https://api.yammer.com/api/v1/messages.json', { body: 'blah blah', group_id: XXXXXXX }, config);
}
I call that scope variable in the view via a button click.
Here is the logic I use to sign the user in:
function checkYammerLogin() {
$scope.Yammer = {};
yam.getLoginStatus(
function (response) {
if (response.authResponse) {
$scope.Yammer = response;
console.dir(response); //print user information to the console
}
else {
yam.platform.login(function (response) {
if (response.authResponse) {
$scope.Yammer = response;
console.dir(response);
}
});
}
}
);
}
I ended up finding the issue.
For some odd reason, every time I would try to use an $http post it would include an Auth token from AD (app using Azure AD for authentication).
I ended up using jQuery inside of my Angular scope function on the button click and it works as I can control the headers for the request.
$.ajax({
url: 'https://api.yammer.com/api/v1/messages.json',
type: 'post',
data: {
body: 'this is a test from jQuery using AngularJS',
group_id: <group_id>
},
headers: {
'Authorization': _token
},
dataType: 'json',
success: function (data) {
console.info(data);
}
});
Fixed the issue and I can now post.
If anyone sees any issues with this practice please let me know, still a little new to angular

How to add text to the body of a CasperJS thenOpen() POST request

I need to write a script inside of datorama.com to access pardot.com. Pardot does have an API that requires a request that has a request inside the body as
POST: https://pi.pardot.com/api/login/version/3
message body: email=&password=&user_key=
Right now here is my code:
phantom.casperPath = casperPath;
phantom.injectJs(casperPath + "/bin/bootstrap.js");
var casper = require('casper').create({
verbose: true,
logLevel: 'debug'
});
casper.start().thenOpen('https://pi.pardot.com/api/login/version/3',{
method: 'post',
content: {
'text' : 'email=<myemail>&password=<password>&user_key=<userKey>'
}
}, function(response) {
this.echo(this.getHTML());
});
casper.run();
I can tell that it is getting through to the server because it is responding this.echo(this.getHTML()); "Login Failed" . I am using the right email/password/user_Key because i am pulling that from the API Console for pardot and it is working there.... So I believe the issue is I am not setting the body of the request correctly.
So does anyone know a way to set the body on the request?
casper.open() or casper.thenOpen() don't understand the content setting. You probably wanted to use data:
casper.start()
.thenOpen('https://pi.pardot.com/api/login/version/3', {
method: 'post',
data: 'email=<myemail>&password=<password>&user_key=<userKey>'
}, function() { ... });
Don't forget to use encodeURIComponent() on the email, password and user key parameters if you build the string yourself.
You can also pass an object:
casper.start()
.thenOpen('https://pi.pardot.com/api/login/version/3', {
method: 'post',
data: {
email: '<myemail>',
password: '<password>',
user_key: '<userKey>'
}
}, function() { ... });
If you expect something else than HTML from the API, then you should use casper.getPageContent() instead of casper.getHTML().

Categories

Resources