I try to use the $resource service with surveygizmo api.
My code :
html :
<div ng-app="Survey">
<body>
<div ng-controller="SurveyCtrl">
{{survey.data.title}}
</div>
</body>
</div>
my script :
angular.module('Survey', ['ngResource']);
function SurveyCtrl($scope, $resource) {
$scope.surveygizmo = $resource('https://restapi.surveygizmo.com/v3/survey/:id',
{id: '#id'},
{get:{method:'JSONP', params: {'user:pass':'xxx#xxxx:xxxx', q:'angularjs', callback:'JSON_CALLBACK'}, isArray:true}});
$scope.survey = $scope.surveygizmo.get({id:xxxx}, function(survey) {
alert('this is ok');
}, function(err){
alert('request failed');
});
}
When i try it, the alert 'request failed' appear in my page. No json result in the page but i can see it in the firebug network menu.
May i miss something?
kalaoke
I know this question is old, but I thought I might be able to help. I actually work at SurveyGimzo. We actually do support JSONP, JSON and XML. However; in order to request JSONP you need to specify this in the url. Using your example URL, it would look like this.
https://restapi.surveygizmo.com/v3/survey/:id.jsonp
Now when you request JSON_CALLBACK as part of the your ngResource parameters for your get action, you will get a properly wrapped object back.
I have been tinkering around with a minnie AngularJS app using SG REST api. You are welcome to take a look at my github https://github.com/sfisherGizmo/ang-app
I hope this helps anyone else who may happen across this as well.
Survey Gizmo does not support JSONP.
HTTP Methods which are supported by Survey Gizmo are
PUT, POST, DELETE
see
http://developer.surveygizmo.com/rest-api-documentation/methods/
Or if they support they did not specify that in the API doc.
this is what i see when u change .get to .query
Request URL:https://restapi.surveygizmo.com/v3/survey/xxxx
Request Method:OPTIONS
Status Code:200 OK
and if you go ahead with .get the response is
Request URL:https://restapi.surveygizmo.com/v3/survey/xxxx
Request Method:GET
Status Code:200 OK
But the response is not wrapped in JSONP callback. Though you are able to see a response in firebug network console but angular is not able to unwrap it since its not a JSONP response.
Check http://jsfiddle.net/jhsousa/aQ4XX/ for angularjs examples using ngResource
Related
I hope you are well. I am working on a project that involves working with the Steam Web API in angular JS. I am trying to fetch the data from this URL:
http://api.steampowered.com/ISteamApps/GetAppList/v2
When I run my code in Google Chrome it shows:
Uncaught SyntaxError: Unexpected token :
I know that there's this issue with CORS(and some sites not playing nice with it so I am trying to work around that using JSONP. Is there something that I am missing or doing wrong?
Kind regards,
Adi
Here's the relevant snippets of code (I have excluded my API Key per the Steam Web API terms):
var steam_api = "https://api.steampowered.com/ISteamApps/GetAppList/v2";
steam_api += "?key=mySteamKey";
steam_api += "&format=json&callback=JSON_CALLBACK";
$scope.steamGames = {};
$http.jsonp(steam_api)
.success(function(data, status, headers, config){
console.log(data);
$scope.steamGames = JSON.parse($scope.rawData);
$scope.steamSearch = document.getElementById('Search').value;
});
Edit: Just for clarity I have also checked with a JSON validator and the JSON that it spews out is valid.
We have an answer. Steam's API does not allow you to send requests to it using CORS (as it does not allow cross origin requests). If you send it via JSONP then you get the unexpected token error like I did. However, there is still hope.
Using a tutorial on CodePen I was able to make the request to the Steam Web API(using my server written in NodeJS) and capture the JSON from the response in a variable. My next course of action will be to somehow send that variable to Angular JS and get the right values out of it using the ng-repeat directive in my HTML. Thanks everyone for your help.
Edit: Here's the link to the CodePen tutorial along with the required nodeJS/ExpressJS code:
https://codepen.io/johnchristopherjones/post/how-do-i-use-the-steam-api-in-my-web-app
app.get('/steam/civ5achievements', function(httpRequest, httpResponse) {
// Calculate the Steam API URL we want to use
var url = 'http://api.steampowered.com/ISteamUserStats/GetSchemaForGame/' +
'v2/?key=YOURSTEAMAPIKEYHERE&appid=8930';
request.get(url, function(error, steamHttpResponse, steamHttpBody) {
// Once we get the body of the steamHttpResponse, send it to our client
// as our own httpResponse
httpResponse.setHeader('Content-Type', 'application/json');
httpResponse.send(steamHttpBody);
});
});
I am working on an app that will submit data to a REST API and have some questions.
How does jQuery know if my post request was successful or not? Is it only looking at the HTTP status?
Is there a convention on what to return from a POST request to a REST API?
JavaScript
$.post( '/API/removeUser', { Eid: id }, function(data) { row.remove(); } );
PHP SLIM Framework
$app->POST('/API/removeUser', function () use ($app) {
// Get the ID from the jQuery post
$Eid = trim(stripslashes(htmlspecialchars($_POST['Eid'])));
echo json_encode(removeFunction($Eid));
});
Your backend should always return the appropriate HTTP status code along with the actual data. 404 for resources that were not found, 403 for unauthorized requests, 200 for successful requests etc. Most AJAX libraries (including jQuery) will rely on those for determining the result of the operation.
If you need more fine-grained error reporting, you could always include a field like "errorCode" in your response that contains an application-level error code that you define yourself and react to accordingly in your frontend code.
I am trying to get information from a fantasy data API using AngularJS. I am using $resource to perform my get request in my controller, but I haven't been able to figure out how to correctly include the API key. Do I need to include it as a header? Thanks.
nflApp.controller('mainController', ['$scope','$resource','$routeParams', function($scope, $resource, $routeParams) {
$scope.fantasyAPI = $resource("https://api.fantasydata.net/nfl/v2/JSON/DailyFantasyPlayers/2015-DEC-28", { callback: "JSON_CALLBACK" }, { get: { method: "JSONP"}});
console.log($scope.fantasyAPI);
}]);
Below is the http request info from the site.
You should set a header with the API key, AngularJS will send them with every request in the following case:
$http.defaults.headers.common["Ocp-Apim-Subscription-Key"] = key;
When adding '.common' you are telling angular to send this in every request so you do not need to add it to every resource that hits the API.
A easy way to do that is by creating your own interceptors from $httpProvider at "config" fase.
To do that, just write something like:
mymodule.config(['$httpProvider', function($httpProvider){
$httpProvider.interceptors.push(function ($q) {
return {
'request': function (config) {
config.headers['Ocp-Apim-Subscription-Key'] = SomeUserClass.AuthToken();
return config;
},
'response': function (response) {
return response;
}
};
});
});
You need to modify request header in JSONP. Unfortunately it is not possible. As the browser is responsible for header creation and you just can't manipulate that when using JSONP method.
how to change the headers for angularjs $http.jsonp
Set Headers with jQuery.ajax and JSONP?
From that link - https://johnnywey.wordpress.com/2012/05/20/jsonp-how-does-it-work/
Why NOT To Use JSONP?
Deciding against using JSONP is directly related to how it works. First of all, the only HTTP method you can use is GET since that is the only method script tags support. This immediately eliminates the use of JSONP as an option to interact with nice RESTful APIs that use other HTTP verbs to do fun stuff like CRUD. And while we’re on the subject of GET, note that using anything other than URL parameters to communicate with the server API (e.g. sending some JSON over) is also not possible. (You could encode JSON as a URL parameter, but shame on you for even thinking that.)
If they only work with header manipulation you will need to do that call from your server side.
I'm just following tutorials and figuring out how to handle get requests in NodeJS.
Here are snippets of my code:
NodeJS:
router.get('/test', function(request, response, next) {
console.log("Received Get Request");
response.jsonp({
data: 'test'
});
});
Angular:
$http.get("http://localhost:3000/test").
success(function(response) {
alert("OK");
}).
error(function(response) {
alert("FAIL");
});
If I try to access the link directly # localhost:3000/test, I'm able to receive the JSON message correctly. But when I use angularJS $http call, the request always fails and I'll find this error in the network inspector (Response)
SyntaxError:JSON.parse:unexpected end of data at line 1 column 1 of
the JSON data
The reason for that is because the response is empty but the response code is 200 in both cases.
I've tried searching for hours but maybe someone can enlighten me on this?
you could try and send
res.send('test')
and then on your http request you can use 'then'
$http.get("http://localhost:3000/test").then(function(res) {
console.log(res);
})
unlike success, then will give you a complete object (with 'test' - string as res.data)
success will bring you only the data;
then will bring you the whole object (with the status and such)..
now about that jsonp .. it's used to override a json response. you could simply use 'res.json({data: 'test'})' and it should also work for you..
hope it helps
You're using jsonp in node, which you probably don't need to. This adds extra characters to the response and so the JSON parser fails to parse (that's what the error is telling you, the JSON is malformed)
Try changing the server to look like
response.json({
data: 'test'
});
If you look in the Network pane of the developer tools, you should be able to see the raw response. It should look something like:
{"data" : "test"}
Using a normal html form, I can add a new task by sending POST request to /api/tasks/insert/
POST data includes $name and $description of the task.
However, when I use Angular to push the data to REST API in php, only a POST request is sent and an empty row is created in the database.
This means that the POST variables are not being passed i.e. name and description.
What am I doing wrong?
I have been stuck at this for the last few hours now. I have checked countless tutorials and am pretty sure of the syntax. My backend REST api in PHP works fine.
var res=$resource('http://localhost/api/tasks/insert/',{},
{
createTask:{method:'POST'}
});
postData={name:"Hello",description:"DescBaby"}
res.createTask({},postData);
//res.createTask(postData); tried this also, but doesn't work
Another variation that I tried based on an comment was this:
res.createTask({name:"TestName", description:"descBaby"}).$promise.then(function(value)
{
console.log("Success"); //I get success in console.
},function(errResponse)
{
console.log("Error");
});
Angular Does not give me any errors. Just sends a blank POST request to the url.
EDIT:
I checked in the network pane in Chrome whether the data was sent or not and as it turns out it is being sent.
However, in the response it's showing this :
Undefined index: name in XYZ.php line ABC.
The line pointed above is the following line in my PHP:
$obj->InsertTask($_POST['name'],$_POST['description']);
Thanks to a friend of mine, I finally got the code running. The problem wasn't with my Angualar Code but with php code.
As it turns out I cannot read POST data as $_POST[].
file_get_contents should be used in such cases as data is sent through a JSON payload and not through request parameters!
Here's how I got it running : Angularjs $http.post, passing array to PHP
Did you look at the network tab of debugger? You can check if valid data was sent to server. If it was ok this is not JS or Angular question. On the first look it seems that you have valid code for angular. Just in case check if you have set proper ajax headers.
"X-Requested-With": "XMLHttpRequest"
Does other AJAX calls work for you?
Try this (and create a factory to follow the best practices):
Service
services.factory("Tasks", function($resource) {
return $resource('http://localhost/api/tasks/insert/', {}, {
createTask: {method:'POST', params: {name:"Hello",description:"DescBaby"}}
})
});
Controller
Tasks.$createTask();